C# - how do I refresh DataGridView after removing rows

岁酱吖の 提交于 2019-12-17 20:37:06

问题


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?


回答1:


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




回答2:


Don't you need to rebind the data grid?

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

?




回答3:


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.




回答4:


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.




回答5:


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




回答6:


this code could be useful:

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

Hope this helps.




回答7:


Try removing the actual items from your binding source instead.



来源:https://stackoverflow.com/questions/1560559/c-sharp-how-do-i-refresh-datagridview-after-removing-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!