C# DataGridView is not updating with DataTable

cdatagridviewdatatable

i have a DataTable with some data and i bind it with my DataGridView with this code:

dataGridView1.DataSource = Measures.Table;

In separate thread i read data from connected device and insert that into my DataTable with this code:

DataRow row = table.NewRow();
row[ "Time" ] = dt;
foreach ( var kvp in measures )
    row[ kvp.Key ] = kvp.Value;
table.Rows.Add( row );

On my Form I am able to change it's main control with a button. Both controls are UserControl, of which one consists the dataGridView1 DataGridView. When I add a row to my DataTable, my DataGridView does not update, until I switch to the other control, and move back to the one with DGV.

I have read some solutions on stack, which basically tell me that i should use BindingSource, but this code:

BindingSource source = new BindingSource();
source.DataSource = Measures.Table;
dataGridView1.DataSource = source;

does not work as well.

I don't know why this happens, because I have also created a simple app with just DGV and DataTable updated with Timer.Tick event and it works there. Anyone knows any reason why this DGV is not updating itself? It updates itself only when forced to redraw (with switching controls or just form resize)

Best Answer

First, a data grid binds to a DataView of a data table, and handles internally to use the source.DefaultView.

After your records are added to the table, issue a refresh via the Items...

dataGridView1.Items.Refresh();

You should not have to rebind the source... just caution if you are doing the items.refresh from a different thread because the grid is UI based and not behind-the-scenes.

Related Topic