ASP.NET Using a Repeater to create a HTML Table

Download ASP.NET for free

Example

When the Repeater is Bound, for each item in the data, a new table row will be added.

<asp:Repeater ID="repeaterID" runat="server" OnItemDataBound="repeaterID_ItemDataBound">
    <HeaderTemplate>
        <table>
            <thead>
                <tr>
                    <th style="width: 10%">Column 1 Header</th>
                    <th style="width: 30%">Column 2 Header</th>
                    <th style="width: 30%">Column 3 Header</th>
                    <th style="width: 30%">Column 4 Header</th>
                </tr>
            </thead>
    </HeaderTemplate>
    <ItemTemplate>
        <tr runat="server" id="rowID">
            <td>
                <asp:Label runat="server" ID="mylabel">You can add ASP labels if you want</asp:Label>
            </td>
            <td>
                <label>Or you can add HTML labels.</label>
            </td>
            <td>
                You can also just type plain text like this.
            </td>
            <td>
                <button type="button">You can even add a button to the table if you want!</button>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>

The ItemDataBound method is optional, yet useful for formatting or populating more complicated data. In this example, the method is used to dynamically give each <tr> a unique ID. This ID can then be use in JavaScript to access or modify a specific row. Note, the tr will not keep its dynamic ID value on PostBack. The text of each row's <asp:Label> was also set in this method.

protected void repeaterID_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        MyItem item = (MyItem)e.Item.DataItem;

        var row = e.Item.FindControl("rowID");
        row.ClientIDMode = ClientIDMode.Static;
        row.ID = "rowID" + item.ID;

        Label mylabel = (Label)e.Item.FindControl("mylabel");
        mylabel.Text = "The item ID is: " + item.ID;
    }
}

If you plan on doing a lot of communication with the CodeBehind, you might want to consider using GridView. Repeaters, however, in general have less overhead than GridView, and with basic ID manipulation, can perform the same functions as GridView.

WebService without Visual Studio