Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 423
Mitja Bonca Avatar asked Dec 24 '12 19:12

Mitja Bonca


2 Answers

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.

like image 66
Chris Doggett Avatar answered Sep 19 '22 01:09

Chris Doggett


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.

like image 40
Mitja Bonca Avatar answered Sep 19 '22 01:09

Mitja Bonca