Monday, July 25, 2011

C# .NET 4 DataGridView doesn't display data after datasource is set

It took me an hour of searching and experimenting to discover the reason why the DataGridView wouldn't display any data when I bound lists of objects to it.

The DataGridView will not auto generate columns or display data of any kind if the objects in the list to which you are binding have only fields and not properties.

To fix the problem add a public property with a getter for each field for which you wish to display a column.

In my case I wasn't interested in properties because the classes in question were DataContracts where the fields were my focus.  The DataContract and DataMember attributes below are not required.

[DataContract]
public class FBAccount
{
     [DataMember(IsRequired = false)]
     public int id;
     public int Id
     {
            get { return id; }
     }
      ...

}

BindToGrid(object DataSource_)
{

            List accounts = DataSource_ as List;

            dataGridView1.AutoGenerateColumns = true;

            BindingSource bs = new BindingSource();

            bs.DataSource = accounts;              

            dataGridView1.DataSource = bs;

            bs.ResetBindings(true);

}

-Chris

No comments: