开发者

BindingList<T> datasource for DataGridView

开发者 https://www.devze.com 2023-01-17 23:48 出处:网络
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.

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.

0

精彩评论

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

关注公众号