So, you wanna do some custom DataBinding?

Another cool feature of the .NET DataGrid is the ability to bind not only to Data* structures ( DataSet, DataTable, etc… ), but also custom objects and structures.

Recently, I needed to bind a DataGrid to a strongly typed collection of domain objects, hereby referred to as ‘DOs’ ( DOS, get it? )

Now, you CAN just set the DataGrid.DataSource property, as such:

     dgMyDataGrid.DataSource = DOs;

However, this will use reflection to name the columns of the DataGrid. So, if you have a property named “ObjectName”, it will show up as an “ObjectName” column. Blah….

But wait, there is a simple solution to your problem: Custom Table styles.

Create a new DataGridTableStyle object, and set the MappingName property to the type of your collection:

     dataGridTableStyle.MappingName = “DomainObject[]“

Notice the array designation. This is VERY important and the one drawback of this whole system. The collection that you bind MUST derive from System.Array in order to make use of your custom styles.

This is easy to accomplish. Let’s say your DomainObjects collection derives from CollectionBase ( as it should…. 😉 ). In order to get a strongly typed array from that collection, execute this command:

     (DomainObject[])InnerList.ToArray(typeof(DomainObject));

There you go. Now, you can create DataGridColumn objects for each column you want to display, then add them to your style. MSDN has TONS of info on this, so I won’t waste time.

Just remember, System.Array != CollectionBase or IList.

Happy Binding.

Ciao