.net – how to delete row from datagridview with a delete button

datagridviewnetwinforms

I've got a DataGridView with a BindingSource binding it to a DataTable. I've put a Delete button on my form and I want it to delete the currently selected row when clicked, something like this:

    if (dgvResourceSettings.CurrentRow != null && !dgvResourceSettings.CurrentRow.IsNewRow)
    {
        bindingSource.RemoveCurrent();
    }

The problem is that the New Row is visible on my datagridview. If the user selects that row and then clicks the Delete button then it deletes the last data row, ie the one above the New Row. The reason it does this is that when the datagridview loses focus it changes the current row to the last data row (if the current row was the New Row). I can verify this by simply tabbing off the datagridview.

So I wonder what the normal way to deal with this is? I know users could just select the row and press the DEL key, but I want to give them a Delete button also.

thanks.

UPDATE: From the answers/comments it seems that this behaviour is normal, so it's hard to have a Delete button and the New Row. I've opted to remove the New Row and have an Add and a Delete button instead.

Best Answer

I have a delete button column in my DataGrid with a button for each row that has it's Tag set to the appropriate item. The click handler then retrieves the tag value and deletes that item. This avoids any issues with selection events, etc.