BindingList<T> datasource for DataGridView
I have a BindingList that I would like to use for a datasource on a DataGrid view.
I added dataGridView1 and button 1 to a form. When I press the button, nothing shows up on the dataGridView. If I use a DataTable for the data source it works fine. I must be missing something simple.public partial class Form1 : Form
{
BindingList<ClassificationInfo> boundList;
ClassificationInfo item;
private void button1_Click(object sender, EventArgs e)
{
boundList = new BindingList<ClassificationInfo>();
item = new ClassificationInfo();
item.bExclude = 1;
item.iColor = 123456;
item.szDescription = "Test line 1";
boundList.Add(item);
item = new ClassificationInfo();
item.bExclude = 0;
item.iColor = 7890123;
item.szDescription = "Test line 2";
item.iOrder = 2;
boundList.Add(item);
dataGridView1.DataSource = boundList;
}
public class ClassificationInfo
{
public int iColor;
public int iOrder;
public string szDescription;
public int bExc开发者_如何学运维lude;
}
}
Turn your public fields on ClassificationInfo into properties.
public class ClassificationInfo
{
public int iColor { get; set; }
public int iOrder { get; set; }
public string szDescription { get; set; }
public int bExclude { get; set; }
}
DataBinding in just about every case relies on a TypeDescriptor, which uses PropertyDescriptors to discover properties. Fields are ignored (as they should be - they should be encapsulated), so your data binding doesn't work.
精彩评论