I want to remove the current selected row from my dataGridView1 when the user presses the DEL button on the keyboard.
Here is my code so far
// Remove selected row
private void DeleteRow()
{
try
{
dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
MessageBox.Show("Row removed");
}
catch (Exception ex)
{
MessageBox.Show("row remove EX");
return;
}
}
// Event when user presses DEL button on keyboard
private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
DeleteRow();
}
The application removes the row but the DeleteRow()
function never executes, since I never see the Row removed
message. Am I missing something?
EDIT: Updated code
From what is visible by the code you posted, you call DeleteRow() from RowsRemoved event handler.
But the RowsRemoved will not execute until a row is deleted. And if it will execute it will directly again delete another row - if there is one or throw an exception.
Please try:
private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
{
MessageBox.Show("row removed").
}
Try to understand what you have coded by setting a debugging breakpoint in DeleteRow(). Currently your application is like DeleteRow->RowRemovedEventHandler->DeleteRow
So your code to remove the row is executed twice.