views:

36

answers:

1

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 bExclude;
    }
}
+1  A: 

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.

Adam Sills
This worked. Thanks. How did you format my post correctly? I thought I posted it between code tags, but the entire block of code wasn't highlighted when it posted.
DarwinIcesurfer
This site doesn't use code tags, not sure where you got that. While you're editing a post, there's a summary on the right of what you can do, or you just click the code button (1s and 0s) in the editor with the code selected (code formatting is 4 spaces at the beginning of the line).
Adam Sills