Error deleting records from a DataGridView

0

My code does not show errors but when I want to use the button, it sends me this error, I would like to know how to solve it.

My "REMOVE" button code

 private void BtnQuitar_Click(object sender, EventArgs e)
  {
      foreach(DataGridViewRow item in DataGridViewSelectionArea.SelectedRows)
      {
          DataGridViewSelectionArea.RemoveAt(item.Index);

      }

    }
    
asked by Alejandro Estupiñán 27.12.2018 в 01:01
source

1 answer

0

If you linked the DataGridView to a origen de datos , you can not delete items directly in the control, you have to delete the row from the DataTable and re-bin so that it is updated

On the other hand, if you define an Id column this should be unique for each item, there I see that you have a 1 as Test and the same 1 for Bar, if it is Id it can not be duplicated, but it stops being Id If you want to use the SelectedRows instead of the check you can search by id, but this should be unique, then you would:

private void BtnQuitar_Click(object sender, EventArgs e)
{
    if(DataGridViewSelectionArea.SelectedRows == null)
    {
       MessageBox.Show("Debe seleccionar un fila del grid");
       return;
    }

    var dt = (DataTable)DataGridViewSelectionArea.DataSource;

    foreach(DataGridViewRow item in DataGridViewSelectionArea.SelectedRows)
    {
        var row = dt.AsEnumerable().FirstOrDefault(r=> r["Id"] == item.Cells["Id"].Value);

        if(row != null)
        {
            dt.Rows.Remove(row);
        }
    }

    DataGridViewSelectionArea.DataSource = dt;

}

The idea is to look in the data that you linked to the Grid to eliminate these and in the end to show them again

    
answered by 27.12.2018 / 01:37
source