"gridview Object does not match target type" error during binding collection of different type objec

G

gui.besse

It seems that we can't bind a collection of instance of different type.

Let's have an example:

// My POCO
public interface ITest
{ string Name { get;set;} }

public class A : ITest
{
private string _name;
public string Name
{
get{ return _name;}
set{ _name = value;}
}

public class B : ITest
{
private string _name;
public string Name
{
get{ return _name;}
set{ _name = value;}
}

// My asp.net page
// 1 - populate my list
List<ITest> myList = new List<ITest>();
A a = new A();
a.Name = "my name is A";
myList.Add(a)

B b = new B();
b.Name = "my name is B";
myList.Add(b);

// the binding with gridview
myGridView.DataSource = myList:
myGridView.DataBind();

generate an exception on the last line:

Object does not match target type.
Exception Details: System.Reflection.TargetException: Object does not
match target type.
[TargetInvocationException: Property accessor 'Name' on object 'B'
threw the following exception:'Object does not match target type.']

Any idea?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top