views:

369

answers:

3

I have an asp:DetailsView with several columns, e.g. Foo, Bar.

I want to fill it with an anonymous type, i.e.:

gridView.DataSource = new { Foo = 1, Bar = "2" };
gridVeew.DataBind();

But getting next error:

Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource.

How can I do what I want?

+2  A: 

The DataSource property expects a collection. The value you are assigning is not a collection.

You will have to create a collection and put the anonymous typed instance into that collection. The following should probably work (though I've not tested it with DataSource):

gridView.DataSource = new[] {new {Foo = 1, Bar = "2"}};
Peter Lillevold
Very strange. I tried it myself, but got the same error. And after that decided to ask help here. So I had to rebuild project or something like that.. Thanks!
abatishchev
Yeah, annoying when that happens! Anyway, glad to be of assistance :)
Peter Lillevold
A: 

You should have a collection containing your anonymous type.
Look at this example I found in this blog

static void Main(string[] args)
{
    var Customer = new { FirstName = "John", LastName = "Doe" };
    var customerList = MakeList(Customer);

    customerList.Add(new { FirstName = "Bill", LastName = "Smith" });
    //then you can bind this collection
    gridView.DataSource = customerList;
    gridVeew.DataBind();
}

public static List<T> MakeList<T>(T itemOftype)
{
    List<T> newList = new List<T>();
    return newList;
}      
Matias
The generic method trick is nice. But in this case unnecessary since the DataSource doesn't require a strongly typed collection.
Peter Lillevold
Right Peter. Your answer is incredibly simple and clever
Matias
+2  A: 

Another solution:

var list = from item in myList 
        select new { Foo = item.Foo, Bar = item.Bar.ToString() };
gridView.DataSource = list;
gridView.DataBind();

Which assumes you have a myList of IEnumerable<T>

Chris S