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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With