How to delete row from datagridview using delete button?

I have a DataGridView with a BindingSource binding it to a DataTable. I put the “Delete” button in my form, and I want it to delete the current selected row when clicked, something like this:

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

The problem is that New Row is visible in my datagridview. If the user selects this row and then clicks the "Delete" button, it deletes the last row of data, that is, 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 row of data (if the current row was a new row). I can verify this by simply dropping the datagridview.

So what is interesting, how is the normal way to handle this? I know that users can simply select a row and press the DEL key, but I also want to give them the "Delete" button.

thanks.

UPDATE. From the responses / comments, it seems that this behavior is normal, so it is difficult to remove the "Delete" and "New line" buttons. I decided to delete the new line and add the Add and Delete button instead.

+3
source share
4 answers

The source should be: "when the datagridview object loses focus, it changes the current row to the last row of data." This is not an ordinary case, you have to do something (keybd events?) For this to happen.

, .

: "New Row", . , , , . CurrentRow null. , .

: (BindingSource) "", . , , ().

, . . BFree .

+1

DataGrid , Tag . . ..

+3

"SelectedRows":

if (this.dataGridView1.SelectedRows.Count > 0)
  {
    foreach (DataGridViewRow dgvrCurrent in dataGridView1.SelectedRows)
  {
    if (dgvrCurrent == dataGridView1.CurrentRow)
      {
        dataGridView1.CurrentCell = null;
      }

    // Delete Row Here
  }
+1

, DataGridView, . Button datagridview, , RowID .

0

Source: https://habr.com/ru/post/1706897/


All Articles