views:

126

answers:

3

Hello, 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.

+1  A: 

Check out BindingList<T>, this is a list that supports databinding and as such it fires off events when the collection is modified.

Will A
All of you are fast than me. Thanks you very much. ^^
Trần Quốc Bình
+1  A: 

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.

p.campbell
I had tried dataGridView1.DataSource = null;dataGridView1.DataSource = list; but it flash the datagridview.
Trần Quốc Bình
A: 

Answer my question. I've tried to use a BindingList<Person> instead of List<Person> and the problem solved.

Trần Quốc Bình