views:

6547

answers:

4

whats the best way to refresh a DataGridView when you update the base 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 made (and it works), but null'ing out the DataGridView.DataSource doesnt 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);
}
A: 

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}
Georg
No such event with dataGridView, dataGridView1.DataBind();
Vikas
A: 

sorry, should have mentioned that this is for a windows app..

databind doesnt exist.

shaunf
+11  A: 

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.

Alan
This is the way I have been doing it for a long time and it seems to work the best. It causes all of your data bound controls to check to see if their data has been updated and then refresh if necessary.
John Chuckran
cheers for validating that. i was hoping you could just change the datasource then perform a refresh of some kind. :Pit just seemed like a logical solution. oh well
shaunf
What's the significance of using 'typeof(List)' instead of null?
GWLlosa
@GWLlosa, if you are using auto generated columns and you set the datasource to NULL it will clear the columns. By using typeof(List) it should maintain the column structure during the refresh. I would personally use AutoGenerateColumns = false; and create the columns on the first pass of the refresh. That way if the user resizes a column it won't toss out their change on refresh.
Chris Porter
+2  A: 

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.

GWLlosa
This is a good suggestion. After that you just have to call .Refresh() for the datagridview to refresh it's data displayed...
veljkoz