我有從 user 獲取這些資訊的表單@ID, @From, @To, @Title, @Message。然后它將它們插入到資料庫表中。
如何使用 洗掉某些資料@ID?用戶將擁有dataGridView1所有的datatable,然后通過獲取CurrentCell它將洗掉這些特定資料。
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * from MessagesTable where [ID]=@ID ";
cmd.Parameters.AddWithValue("@ID", id);
MessageBox.Show("Message was deleted");
BindGrid();
}
uj5u.com熱心網友回復:
你幾乎可以肯定這一切都是錯誤的。你應該從一個DataTable. Fill如果合適,您可以通過呼叫資料配接器來查詢資料庫以填充它。DataGridView然后,您可以通過 a將表格系結到您的BindingSource,您將在設計器中添加它,例如
var table = new DataTable();
using (var adapter = new SqlDataAdapter("SQL query here", "connection string here"))
{
adapter.Fill(table);
}
BindingSource1.DataSource = table;
DataGridView1.DataSource = BindingSource1;
然后,您通過呼叫 將當前行標記為已RemoveCurrent洗掉BindingSource。這將隱藏網格中的行,但不會影響該階段的資料庫。要保存對資料庫的更改,您需要呼叫Update適當配置的資料配接器,它可能與您一開始呼叫的資料配接器相同Fill。您可以在用戶洗掉該行后立即呼叫Update以保存更改,或者您可以在本地快取所有更改 - 插入、更新和洗掉 - 然后Update在最后呼叫一次以將所有更改保存在一起。
uj5u.com熱心網友回復:
添加 cmd.ExecuteNonQuery();
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from MessagesTable where [ID]=@ID ";
cmd.Parameters.AddWithValue("@ID", id);
cmd.ExecuteNonQuery();
MessageBox.Show("Message was deleted");
BindGrid();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/479621.html
