开发者

Refresh datagridview in windows form application

开发者 https://www.devze.com 2023-01-11 23:50 出处:网络
I have a form with datagridview and a List like this: private void Form1_Load(object sender, EventArgs e)

I have a form with datagridview and a List like this:

private void Form1_Load(object sender, EventArgs e)
    开发者_如何学C    {
            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.


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


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.


Use this it worked for me:

qTableAdapter.Fill(_11DataSet.q);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消