Question

In my code I need to remove rows from the DataGridView after a recurring interval, and so I call the following function when a timer expires:

private void removeRows(DataGridView dgv) {

    foreach (DataGridViewRow row in dgv.Rows)
    {
        // if some condition holds
        dgv.Remove(row);                
    }
    dgv.Refresh();

}

I know the rows are successfully deleted from the DataGridView, though they still remains in the display for whatever reason. Any tips on what I might be doing wrong?

Was it helpful?

Solution

If you have bound your datagrid to an Observable Collection (if not then you should) then you will need to implement INotifyCollectionChanged interface so that listeners are notified of dynamic changes, such as when items get added and removed or the whole list is refreshed.

HTH

OTHER TIPS

Don't you need to rebind the data grid?

dgrv.Datasource = [whatever data source];
dgrv.DataBind();

?

Sometimes refreshing the data gridview is not enough and its containing parent should be refreshed too.

Try this:

dgv.Refresh(); // Make sure this comes first
dgv.Parent.Refresh(); // Make sure this comes second

You could also edit your source and attach the new datasource to the control.

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.

If it's a data-bound grid, you should be working on the binding source itself instead of the grid.

this code could be useful:

dataGridView.DataSource = null;
dataGridView.Update();
dataGridView.Refresh();
dataGridView.DataSource = SomeDataSource;

Hope this helps.

Try removing the actual items from your binding source instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top