C# - how do I refresh DataGridView after removing rows
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?
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.
this code could be useful:
dataGridView.DataSource = null;
dataGridView.Update();
dataGridView.Refresh();
dataGridView.DataSource = SomeDataSource;
Hope this helps.
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
If I understand you correctly, you want to delete rows selected by a user from your DGV.
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.
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)
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.
Try removing the actual items from your binding source instead.
I had same problem and I have find out the root cause. all you have to do initialize you database context object in before reload and see the magic .
精彩评论