Search code examples
c#asp.netrepeater

Optimize asp.net C# code for repeaters using a table


On the aspx:

<table>
<tr>
<asp:Repeater ID="rptHeader" runat="server">
    <ItemTemplate>
        <th><%#Eval("Category")%></th>
    </ItemTemplate>
</asp:Repeater>
</tr>
<tr>
<asp:Repeater ID="rptContents" runat="server">
    <ItemTemplate>
        <td valign="top">
            <%#Eval("Content")%>
        </td>
    </ItemTemplate>
</asp:Repeater>
</tr>
</table>

On the code-behind:

protected void Page_Load(object sender, EventArgs e) 
{
    rptHeader.DataSource = DataSource;
    rptHeader.DataBind();
    rptContentBlocks.DataSource = DataSource;
    rptContentBlocks.DataBind();
}

The problem here is that instead of using Two repeaters, can we use only one? We actually need the header to be separated from the contents using a different table row...

Edit: changed rptHeader's ItemTemplate's html element from <td> to <th> to be a little clearer. :-)


Solution

  • IMO it's impossible without repeater hacking. Anyway, there is a rather irregular approach that maybe works. Also you can use two foreach statements instead of repeaters.

    Code

    protected string[] headers = { "A", "B", "C", "D" };
    protected string[] contents = { "Alpha", "Beta", "Counter", "Door" };
    
    //string[] headers = { "A", "B", "C", "D" };
    //string[] contents = { "Alpha", "Beta", "Counter", "Door" };
    
    //DataList1.RepeatColumns = headers.Length;
    //DataList1.DataSource = headers.Concat(contents);
    //DataList1.DataBind();
    

    Html markup

    <table>
        <tr>
            <%foreach (string item in headers)
              { %>
              <th><%= item %></th>
            <% } %>
        </tr>
        <tr>
            <%foreach (string item in contents)
              { %>
              <td><%= item %></td>
            <% } %>
        </tr>
    </table>
    <!--
        <asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal">
            <ItemTemplate>
                <%# Container.DataItem %>
            </ItemTemplate>
        </asp:DataList>
    -->