Developer's Corner

by Antonio Bello

DataGridView: How to Bind Nested Objects

| Comments

The WinForms DatagridView control is not capable of handling nested properties, as it works with base data types only. But implementing such feature is not complicated. Let’s see how.

The Problem

A DataGridView can be bound to a collection of objects to display any of its base data type (i.e. string, int, and so on) properties. For example, a collection of instances of the following class:

1
2
3
4
5
6
7
8
public class Customer
{
  public string FirstName { get; set;}
  public string LastName { get; set;}
  public string Street { get; set;}
  public string PostalCode { get; set;}
  public string City { get; set;}
}

can be used to display any of the Customer class properties in the DataGridView.

But what happens when the class exposes other objects which are not base data type? If an Address class is created and used as a property of the Customer class:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Address
{
  public string Street { get; set;}
  public string PostalCode { get; set;}
  public string City { get; set;}
}

public class Customer
{
  public string FirstName { get; set;}
  public string LastName { get; set;}
  public Address Address { get; set;}
}

a DataGridView bound to a collection of Customer instances is not able to display any of the Address properties. In such cases the displayed cells are empty.

The Solution

In order to enable the DataGridView to display properties exposed by class members, some custom development is required. The first step is to implement the DataGridView’s CellFormatting event handler

1
2
3
4
5
6
private void gridCustomers_CellFormatting(
  object sender,
  DataGridViewCellFormattingEventArgs e)
{
  ...
}

The CellFormatting event handler needs to differentiate whether the field to be displayed is one of the base data type or an object exposing its own properties. This is achieved by looking for the dot character ‘.’ in the column’s DataPropertyName field:

1
2
3
4
5
6
7
8
9
10
private void gridCustomers_CellFormatting(
  object sender,
  DataGridViewCellFormattingEventArgs e)
{
  if ((gridCustomers.Rows[e.RowIndex].DataBoundItem != null) &&
      (gridCustomers.Columns[e.ColumnIndex].DataPropertyName.Contains(".")))
  {
    ...
  }
}

If the DataPropertyName field doesn’t contain a dot character, then the actual value of the base data type property must be displayed – in this case no action is required, since it is already filled in e.Value.

On the other hand, if the DataPropertyName field contains one or more dot characters, then it points to a property exposed by one of the bound class properties. For example, Address.Street contains the dot character, and it points to the Street property of the Address property of a Customer instance. To handle this cases, a recursive function BindProperty is used:

1
2
3
4
5
6
7
8
9
10
11
12
13
private void gridCustomers_CellFormatting(
  object sender,
  DataGridViewCellFormattingEventArgs e)
{
  if ((gridCustomers.Rows[e.RowIndex].DataBoundItem != null) &&
      (gridCustomers.Columns[e.ColumnIndex].DataPropertyName.Contains(".")))
  {
  e.Value = BindProperty(
                gridCustomers.Rows[e.RowIndex].DataBoundItem,
                gridCustomers.Columns[e.ColumnIndex].DataPropertyName
              );
  }
}

The BindProperty function resolves the data property name and provides the actual value to be displayed in the grid cell by using reflection and (if required) recursion. Two arguments are passed to the BindProperty method: the class property value (which is an instance of a class, in the above example an instance of the Address class) and the DataPropertyName:

1
2
3
4
private string BindProperty(object property, string propertyName)
{
  ...
}

The first thing to check is whether the property name contains the dot character – although this never happen when called directly from the CellFormatting event handler, since the if statement prevent this, it may happen when BindProperty calls itself recursively.

1
2
3
4
5
6
7
8
9
10
11
private string BindProperty(object property, string propertyName)
{
  if (propertyName.Contains("."))
  {
    ...
  }
  else
  {
    ...
  }
}

If the property name doesn’t contain any dot character, then the propertyName variable contains the name of the property object to be displayed in the grid.

Reflection is used to read the property value, obtained by retrieving the PropertyInfo from the property variable, and then getting the property value by calling the GetValue() method of the PropertyInfo instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private string BindProperty(object property, string propertyName)
{
  string retValue = "";

  if (propertyName.Contains("."))
  {
    ...
  }
  else
  {
    Type propertyType;
    PropertyInfo propertyInfo;

    propertyType = property.GetType();
    propertyInfo = propertyType.GetProperty(propertyName);
    retValue = propertyInfo.GetValue(property, null).ToString();
  }
}

This completes the else branch. As for the if branch, it is executed when the property name contains at least one dot character. In this case, still using reflection, the PropertyInfo of the desired property is retrieved, and using recursion, passed to the same BindProperty function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
private string BindProperty(object property, string propertyName)
{
  string retValue = "";

  if (propertyName.Contains("."))
  {
    PropertyInfo[] arrayProperties;
    string leftPropertyName;

    leftPropertyName = propertyName.Substring(0, propertyName.IndexOf("."));
    arrayProperties = property.GetType().GetProperties();

    foreach (PropertyInfo propertyInfo in arrayProperties)
    {
      if (propertyInfo.Name == leftPropertyName)
      {
        retValue = BindProperty(
          propertyInfo.GetValue(property, null),
          propertyName.Substring(propertyName.IndexOf(".") + 1));
        break;
      }
    }
  }
  else
  {
    Type propertyType;
    PropertyInfo propertyInfo;

    propertyType = property.GetType();
    propertyInfo = propertyType.GetProperty(propertyName);
    retValue = propertyInfo.GetValue(property, null).ToString();
  }

  return retValue;
}

The leftPropertyName variable holds the name of the leftmost property, for instance if propertyName is Address.Street, it is filled in with Address. By looping through the array of PropertyInfo of the property object, the PropertyInfo instance of the leftPropertyName property is retrieved. Then, BindProperty is called again, passing the instance of the leftPropertyName property and the right part of propertyName (for instance, in Address.Street the provided property name is Street).

Souce code available on github: DataGridViewSample

Comments