Binding a generic list to a repeater - ASP.NET

DotnetDude picture DotnetDude · Mar 23, 2009 · Viewed 116.9k times · Source

I am trying to bind a List<AreaField> to a repeater. I have converted the list into an array by using the ToArray() method and now have a array of AreaField[]

Here's my class hierarchy

public class AreaFields
{
    public List<Fields> Fields { set; get; }
}

public class Fields
{
    public string Name { set; get; }
    public string Value {set; get; }
}

In the aspx, I would like to bind it a repeater (something like this)

DataBinder.Eval(Container.DataItem, "MyAreaFieldName1")

The MyAreaFieldName1 is the value of the Name property in the AreaFieldItem class.

Answer

Solburn picture Solburn · May 18, 2010

It is surprisingly simple...

Code behind:

// Here's your object that you'll create a list of
private class Products
{
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public string ProductPrice { get; set; }
}

// Here you pass in the List of Products
private void BindItemsInCart(List<Products> ListOfSelectedProducts)
{   
    // The the LIST as the DataSource
    this.rptItemsInCart.DataSource = ListOfSelectedProducts;

    // Then bind the repeater
    // The public properties become the columns of your repeater
    this.rptItemsInCart.DataBind();
}

ASPX code:

<asp:Repeater ID="rptItemsInCart" runat="server">
  <HeaderTemplate>
    <table>
      <thead>
        <tr>
            <th>Product Name</th>
            <th>Product Description</th>
            <th>Product Price</th>
        </tr>
      </thead>
      <tbody>
  </HeaderTemplate>
  <ItemTemplate>
    <tr>
      <td><%# Eval("ProductName") %></td>
      <td><%# Eval("ProductDescription")%></td>
      <td><%# Eval("ProductPrice")%></td>
    </tr>
  </ItemTemplate>
  <FooterTemplate>
    </tbody>
    </table>
  </FooterTemplate>
</asp:Repeater>

I hope this helps!