Ken Falk - Software Developer

Login
  My Approach     Services     Contact     Experience     Resume     Blog    
 

Data binding a Generic List to a Control

So, maybe you know that you can create a collection of type:

List<string>

or in VB

List(Of String)

For Example (you have a repater names rpt):

List<string> lstStuff = new List<string>(); lstStuff.Add("Dog"); lstStuff.Add("Cat"); lstStuff.Add("Pig"); lstStuff.Add("Cow"); rpt.DataSource = lstStuff; rpt.DataBind();

Search for Generic Classes if your not familiar with this.

I generally use custom classes for most of what I do but just instantiating a variable of type List<string> is sure useful sometimes.

So the question came up for the first time for me a few weeks ago about how to DataBind this type of collection. The problem is that the instance of List<string> does not have properties that can be referenced using the Eval function. The answer is you use Container.DataItem.   Below is an example using a repeater but it works the same with a GridView or any other databound control.

<asp:Repeater ID="rpt" runat="server"> <ItemTemplate> <p> <%# Container.DataItem %> </p> </ItemTemplate> </asp:Repeater>