DataGridView.Rows.RemoveAt(int index) doesn't remove row in windows form?

14,814

Solution 1

I think the solution depends on how you bind the data. If you are binding a BindingList, RemoveAt() method removes handles everything for you and you don't have to refresh the DataGridView.

Try below and see...

dataGridView1.Refresh();

OR re-bind the data and see..

dataGridView1.DataSource = myDataSource;
dataGridView1.Refresh();

Solution 2

remove the item from the datasource, and bind again.

since the data comes from linq, before binding, you can do:

var result = fooLinq.ToList();
dataGridView1.DataSource = result;


//to remove and bind again
var result = dataGridView1.DataSource as List<FooType>;
result.RemoveAt(fooIndex);
dataGridView1.DataSource = result;

Solution 3

If I understand you correctly, you want to delete rows selected by a user from your DGV.

  1. Use the DataGridViewRowCollection of your DGV rather than the DataRowCollection of the DataTable. The DataGridViewRow has the Selected property that indicates whether a row is selected or otherwise.

  2. Once you have determined that a row is to be deleted, you can use the Remove method of the DataGridViewRowCollection to delete the item from the grid, e.g. YerDataGridView.Rows.Remove(row)

  3. Note that at this point, although the item is removed from the DGV, it still has not been deleted from the Access DB. You need to call the TableAdapter Update method on your DataSet/DataTable to commit the deletions to the DB, e.g. YerTableAdapter.Update(YerDataSet)

I normally would call Update once to commit the changes only after having removed all the items to be deleted from the DGV.

Share:
14,814
JatSing
Author by

JatSing

Updated on June 05, 2022

Comments

  • JatSing
    JatSing almost 2 years
    int i = dataGridView1.CurrentRow.Index;
    dataGridView1.Rows.RemoveAt(i);
    

    The above code for deleting current selected row (only allow to select 1 row) but I still can see the row remains in datagridview. Did I miss an update or invalidate ?

    ps: dataGridView1 is data-bound.

    ps2: I use linq query to bind data and I don't want to query again for just to show a row was deleted, I think it will slow down performance.