Reputation: 219
I have a form with datagridview and a List like this:
private void Form1_Load(object sender, EventArgs e)
{
List<Person> list = new List<Person>();
list.Add(new Person("A", "An Giang"));
list.Add(new Person("B", "TP HCM"));
list.Add(new Person("C", "Tiền Giang"));
list.Add(new Person("D", "Cần Thơ"));
this.dataGridView1.DataSource = list;
list.Add(new Person("E", "Bạc Liêu")); // --> changed
this.dataGridView1.EndEdit();
this.dataGridView1.Refresh();
this.Refresh();
this.dataGridView1.Parent.Refresh();
}
My problem is the datagridview didn't show the new row although its Datasource had changed. I try to refresh the datagrid but it did not work.
Upvotes: 1
Views: 7762
Reputation: 219
Answer my question. I've tried to use a BindingList<Person>
instead of List<Person>
and the problem solved.
Upvotes: 0
Reputation: 100647
A quick hack shows that this will rebind as you expect with your List<t>
:
...
list.Add(new Person("E", "Bạc Liêu")); // --> changed
dataGridView1.DataSource = null;
dataGridView1.DataSource = list;
Consider refactoring to use a BindingList<Person>
instead of the List<Person>
, which will perform as you expect, and you'll require none of the code to refresh. Implement this change, and all the code after inserting Person E can be deleted.
Upvotes: 1
Reputation: 25018
Check out BindingList<T>
, this is a list that supports databinding and as such it fires off events when the collection is modified.
Upvotes: 3