Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh DataGridView when updating data source

What is the best way to refresh a DataGridView when you update an underlying data source?

I'm updating the datasource frequently and wanted to display the outcome to the user as it happens.

I've got something like this (and it works), but setting the DataGridView.DataSource to null doesn't seem like the right way.

List<ItemState> itemStates = new List<ItemState>(); dataGridView1.DataSource = itemStates;  for (int i = 0; i < 10; i++) {      itemStates.Add(new ItemState { Id = i.ToString() });     dataGridView1.DataSource = null;     dataGridView1.DataSource = itemStates;     System.Threading.Thread.Sleep(500); } 
like image 514
shaunf Avatar asked Oct 31 '08 15:10

shaunf


People also ask

How to refresh a DataGridView?

1) Call the EndCurrentEdit() method of the DataGridView's BindingContext. 2) Refresh first the DataGridView and then the Parent (usually the Form) . Thank you for your response.

What is DataGridView in C#?

The DataGridView control provides a customizable table for displaying data. The DataGridView class allows customization of cells, rows, columns, and borders through the use of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor.


2 Answers

I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a List. Use a BindingList. The BindingList has events that fire when items are added or changed, and the DataGridView will automatically update itself when these events are fired.

like image 154
GWLlosa Avatar answered Sep 21 '22 17:09

GWLlosa


Well, it doesn't get much better than that. Officially, you should use

dataGridView1.DataSource = typeof(List);  dataGridView1.DataSource = itemStates; 

It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.

like image 40
Alan Avatar answered Sep 18 '22 17:09

Alan