1

In a .NET 3.5 winforms application I have a DataGridView component that uses a TableAdapter to a MySQL database.

I am able to add a new record by adding code to the BindingSource_AddingNew event.

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());
    }
}

and I am able to update a record by adding code to the BindingSource_CurrentItemChanged event.

private void someBindingSource_CurrentItemChanged(object sender, EventArgs e)
{
    DataRow ThisDataRow = ((DataRowView)((BindingSource)sender).Current).Row;
    if (ThisDataRow.RowState == DataRowState.Modified)
    {
        someTableAdapter.Update(ThisDataRow);
    }
}

How do I handle a delete event?

** UPDATE 1 **

To handle a delete event a button was added (you need to select the row before pressing the button):

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 Answer 1

2

You are looking for DataGridView.UserDeletingRow event.

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

}
Sign up to request clarification or add additional context in comments.

1 Comment

@Hiremath - You are correct for removing the row from the datagridview. I updated my answer to show how it was possible to remove the record from the underlying database also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.