Binding a object with a sub objects as properties to a datagrid

user26901 picture user26901 · Jan 2, 2009 · Viewed 8.2k times · Source

I am working with an object which has sub objects within (see example below). I am attempting to bind a List<rootClass> to the datagrid. When I bind the List<>, in the cell that contains the subObject, I see the following value ... "namespace.subObject" ... the string values display correctly.

Ideally I would like to see the “Description” property of the subObject in the datacell. How can I map the subObject.Description to show in the datacell?

public class subObject
{
   int id;
   string description;

   public string Description
   { get { return description; } }
}

public class rootClass
{
   string value1;
   subObject value2;
   string value3;

   public string Value1
   { get { return value1; } }

   public subObject Value2
   { get { return value2; } }

   public string Value3
   { get { return value3; } }
}

Answer

Marc Gravell picture Marc Gravell · Jan 3, 2009

Since you mention DataGridViewColumn (tags), I assume you mean winforms.

Accessing sub-properties is a pain; the currency-manager is bound to the list, so you only have access to immediate properties by default; however, you can get past this if you absolutely need by using a custom type descriptor. You would need to use a different token too, like "Foo_Bar" instead of "Foo.Bar". However, this is a major amount of work that requires knowledge of PropertyDescriptor, ICustomTypeDescriptor and probably TypeDescriptionProvider, and almost certainly isn't worth it,

The simplest fix is to expose the property as a shim / pass-thru:

public string Value2Description {
    get {return Value2.Description;} // maybe a null check too
}

Then bind to "Value2Description" etc.