WinForms + DataGridView binding to a List

data-bindingwinforms

I'm trying to bind a List<T> to a DataGridView control, and I'm not having any luck creating custom bindings.

I have tried:

gvProgramCode.DataBindings.Add(new Binding("Opcode",code,"Opcode"));

It throws an exception, saying that nothing was found by that property name.

The name of the column in question is "Opcode". The name of the property in the List<T> is Opcode.

ANSWER EDIT: the problem was that I did not have the bindable fields in my class as properties, just public fields…Apparently it doesn't reflect on fields, just properties.

Best Answer

Is the property on the grid you are binding to Opcode as well?.. if you want to bind directly to List you would just DataSource = list. The databindings allows custom binding. are you trying to do something other than the datasource?

You are getting a bunch of empty rows? do the auto generated columns have names? Have you verified data is in the object (not just string.empty) ?

    class MyObject
    {
        public string Something { get; set; }
        public string Text { get; set; }
        public string Other { get; set; }
    }

    public Form1()
    {
        InitializeComponent();

        List<MyObject> myList = new List<MyObject>();

        for (int i = 0; i < 200; i++)
        {
            string num = i.ToString();
            myList.Add(new MyObject { Something = "Something " + num , Text = "Some Row " + num , Other = "Other " + num  });
        }

        dataGridView1.DataSource = myList;
    }

this should work fine...