Search code examples
c#asp.netrepeater

Binding a generic list to a repeater - ASP.NET


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.


Solution

  • You may want to create a subRepeater.

    <asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
      <ItemTemplate>
        <span><%# Eval("Name") %></span>
      </ItemTemplate>
    </asp:Repeater>
    

    You can also cast your fields

    <%# ((ArrayFields)Container.DataItem).Fields[0].Name %>
    

    Finally you could do a little CSV Function and write out your fields with a function

    <%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>
    
    public string GetAsCsv(IEnumerable<Fields> fields)
    {
      var builder = new StringBuilder();
      foreach(var f in fields)
      {
        builder.Append(f);
        builder.Append(",");
      }
      builder.Remove(builder.Length - 1);
      return builder.ToString();
    }