Monday, January 26, 2009

How to bind a List with custom objects to a Gridview

Curt Christianson told me in his interview that he uses Lists of custom objects as a datasource for his controls.

I wrote a little demo to try it myself. I binded a List of custom objects to a GridView. This shows again what a powerful control the GridView is. You can bind anything to it, as long as it implements IEnumerable. Here is the tutorial.

First I added one folder called BLL (Business Logic Layer). It would be better to put this layer into a different project, but this isn't necessary and would only complicate the tutorial.

In the BLL I added a class Person and I added a class Persons with one method which returns a dummy list of Persons.



Person.cs



Persons.cs

In the code-behind of the Default.aspx, I simple referenced to the namespace ListDemoCsharp.BLL, hooked up the list of Persons to a GridView, and databinded that GridView.



Default.aspx

And that's it! I'm going to experiment with it a little more, because you need to handle sorting/paging yourself.

No comments:

Post a Comment