Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the DataSource on a WinForms DataGridView?

I populate the GridView.DataSource from a EntityFramework Model:

gwTimeLog.DataSource = _entities.TimeLogs;

When a new row is added to the _entities, I try to update the grid (tried using the same statement as above, setting it null, then back to _entities.TimeLogs, etc...), but the grid simply won't update. Even though _entities.TimeLogs actually does contain the new rows.

What am I missing?

like image 711
AngryHacker Avatar asked Jan 06 '10 18:01

AngryHacker


People also ask

How do you refresh or show immediately in DataGridView after inserting?

by adding grdPatient. Update(); and grdPatient.

What is datasource in DataGridView?

The DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces: The IList interface, including one-dimensional arrays. The IListSource interface, such as the DataTable and DataSet classes.


2 Answers

OLD ANSWER: Did you try calling GridView.DataBind()?

Woops, I thought this was a WebForms DataGrid.

If you're on WinForms, you might want to look into the BindingSource class. Binding to that class instead of straight to your list will provide update notification, etc.

The following code works for me:

        List<Person> names = new List<Person>();
        names.Add(new Person(){
            FirstName = "Steve",
            LastName = "Jobs"
        });
        names.Add(new Person()
        {
            FirstName = "Bill",
            LastName = "Gates"
        });

        BindingSource source = new BindingSource();
        source.DataSource = names;
        dataGridView1.DataSource = source;

        names.Add(new Person()
        {
            FirstName = "Steve",
            LastName = "Balmer"
        });

        source.ResetBindings(false);
like image 107
hackerhasid Avatar answered Sep 28 '22 08:09

hackerhasid


The answer is to have the gridview connected to the BindingList rather than the List.

like image 33
AngryHacker Avatar answered Sep 28 '22 08:09

AngryHacker