通过C#DataGridView删除数据库行?

时间:2011-03-17 18:01:27

标签: c# winforms .net-3.5 datagridview

在.NET 3.5 winforms应用程序中,我有一个DataGridView组件,它使用TableAdapter到MySQL数据库。

我可以通过向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);

             }
         }

1 个答案:

答案 0 :(得分:2)

您正在寻找DataGridView.UserDeletingRow活动。

private void DataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
{
    // It is a cancellable event, you could cancel the delete on certain conditions.
    e.Cancel = true;

}