ASP.NET Using a Repeater to create a HTML Table


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">
                    <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 runat="server" id="rowID">
                <asp:Label runat="server" ID="mylabel">You can add ASP labels if you want</asp:Label>
                <label>Or you can add HTML labels.</label>
                You can also just type plain text like this.
                <button type="button">You can even add a button to the table if you want!</button>

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.