使用 Repeater 创建 HTML 表

当 Repeater 绑定时,对于数据中的每个项目,将添加一个新的表格行。

<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>

ItemDataBound 方法是可选的,但对于格式化或填充更复杂的数据非常有用。在该示例中,该方法用于动态地为每个 <tr> 提供唯一 ID。然后,可以在 JavaScript 中使用此 ID 来访问或修改特定行。注意,tr 不会在 PostBack 上保留其动态 ID 值。每行的 <asp:Label> 的文本也在此方法中设置。

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;
    }
}

如果你计划与 CodeBehind 进行大量通信,则可能需要考虑使用 GridView。但是,中继器通常比 GridView 具有更少的开销,并且通过基本 ID 操作,可以执行与 GridView 相同的功能。