Binded DataGridView to List<T> not showing data

This is the code I have (it a very simple example):

public partial class Form1 : Form
{
    List<Person> listPersons;
    public Form1()
    {
        InitializeComponent();
        listPersons = new List<Person>();
        dataGridView1.DataSource = listPersons;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.Text.Length > 0)
        {
            Person p = new Person();
            p.Name = textBox1.Text;
            listPersons.Add(p);
        }
    }
}

class Person
{
    public string Name { get; set; }
}

When you press the button, data IS added to the list, but it doesn't show up in the DataGridView . What am I missing?

I have tried setting AutoGenerateColumns and VirtualMode to true , but that didn't resolve the issue either.


It's been awhile, and I've switched jobs since working on WinForms code that tried to bind List<T>s to DataGridViews. If I recall correctly, whatever you bind needs to implement IBindingList, which List<T> doesn't. I may be wrong on that.

In any case, what I used was BindingListView, which was incredibly fast and easy. You just do:

List<Customer> customers = GetCustomers();
BindingListView<Customer> view = new BindingListView<Customer>(customers);
dataGridView1.DataSource = view; 

And you're done. I haven't looked at the source in a few years, but I believe it wraps the List<T> with a class that implements IBindingList.


But if I use only BindingList<T> instead of List<T> it does work.

Example code:

    BindingList<Person> bl;
    public Form1()
    {
        InitializeComponent();
        bl = new BindingList<Person>();
        dataGridView1.DataSource = bl;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (textBox1.Text.Length > 0)
        {
            Person p = new Person();
            p.Name = textBox1.Text;
            bl.Add(p);
            textBox1.Text = "";
            textBox1.Focus();
        }
    }    

But I would still like to figure out how to show data in DataGridView after bindng it with List.


集中您的FillGrid功能并在您想更新网格时调用它

public Form1()
{
    InitializeComponent();
     listPersons = new List<Person>();

    FillGrid();
}

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text.Length > 0)
    {
        Person p = new Person();
        p.Name = textBox1.Text;
        listPersons.Add(p);

        FillGrid();
    }
}

private void FillGrid()
{
   dataGridView1.DataSource = listPersons;
}
链接地址: http://www.djcxy.com/p/67968.html

上一篇: 申请中的请求对象

下一篇: 将DataGridView绑定到List <T>不显示数据