简体   繁体   中英

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.

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.

  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, eg 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, eg 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.

如果它是一个数据绑定网格,您应该使用绑定源本身而不是网格。

this code could be useful:

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

Hope this helps.

请尝试从绑定源中删除实际项目。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM