views:

77

answers:

2

Say I have these 3 classes:

public class ClassParent  
{  
public string TestParent { get; set; }  
}

public class ClassChild1 : ClassParent   
{   
public string TestChild1 { get; set; }   
}

public class ClassChild2 : ClassParent
{  
public string TestChild2 { get; set; }  
}

Say, I've created plenty of objects of type ClassChild1 and ClassChild2 that I've stored in this List:
List< ClassParent> _Test;

I want to bind this list to a GridView
MyGridView.DataSource=_Test;

This works but it only shows one field in the grid (the TestParent property which is in the ClassParent class). I understand why: the list is made of 'ClassParent' objects so the binding is only done with the properties of that class. The thing is the objects of type ClassChild1 and ClassChild2 inherit from ClassParent.

My question is: if I have a list of objects of different type but which all inherit from the same class, how I can bind all the properties to the grid?

A: 

You can create the columns manually rather than having them inferred from the type. That way, you can bind to whatever properties you want.

HTH, Kent

Kent Boogaart
+1  A: 

The properties have to be present in the base class. Otherwise, how would you access them in a subclass where they're not defined? (What would you like the grid to show for ClassChild2.TestChild1?)

One way around this to fit your model that should work is to define TestChild1 and TestChild2 as virtual properties of your ClassParent object, then override them in the children:

public class ClassParent  
{  
    public string TestParent { get; set; }  
    public virtual string TestChild1 { get {return null;}}
    public virtual string TestChild2 { get {return null;}}  
}

public class ClassChild1 : ClassParent   
{   
    public override string TestChild1 { get; set; }   
}

public class ClassChild2 : ClassParent
{  
    public override string TestChild2 { get; set; }  
}
lc