1
在.NET 3.5 winforms應用程序中,我有一個DataGridView
組件,它使用TableAdapter
來連接MySQL數據庫。通過C#DataGridView刪除數據庫行?
我可以通過向BindingSource_AddingNew
事件添加代碼來添加新記錄。
private void someBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
DataRow ThisDataRow = ((DataRowView)((BindingSource)sender).Current).Row;
if (ThisDataRow.RowState == DataRowState.Added)
{
someTableAdapter.Insert(ThisDataRow.ItemArray[1].ToString());
}
}
我可以通過向BindingSource_CurrentItemChanged
事件添加代碼來更新記錄。
private void someBindingSource_CurrentItemChanged(object sender, EventArgs e)
{
DataRow ThisDataRow = ((DataRowView)((BindingSource)sender).Current).Row;
if (ThisDataRow.RowState == DataRowState.Modified)
{
someTableAdapter.Update(ThisDataRow);
}
}
如何處理刪除事件?
**更新1 **
爲了應對加入一個按鈕刪除事件(你需要按下按鈕,前選擇行):
private void btnDelete_Click(object sender, EventArgs e)
{
Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);
if (selectedRowCount > 0)
{
for (int i = 0; i < selectedRowCount; i++)
{
//delete from database
someTableAdapter.Delete(Convert.ToUInt16(dataGridView1.Rows[dataGridView1.SelectedRows[i].Index].Cells[0].Value));
//refresh datagridview
this.dataGridView1.Rows.RemoveAt(this.dataGridView1.SelectedRows[i].Index);
}
}
@Hiremath - 您無法從datagridview中移除該行。我更新了我的答案,以顯示如何從底層數據庫中刪除記錄。 – 2011-03-18 13:06:05