需求:Repeater 繫結資料時,每 5 筆資料插入一條分隔線 (或空白區塊)。可在 ItemDataBound 事件中依 ItemIndex 判斷動態加入 LiteralControl,或在前端模板使用 CSS :nth-child 純樣式實現 (推薦)。
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptList.DataSource = GetTable();
rptList.DataBind();
}
}
protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var drv = (DataRowView)e.Item.DataItem;
var ltl = (Literal)e.Item.FindControl("ltlTitle");
ltl.Text = drv["title"].ToString();
// 每 5 筆且非最後一筆 插入分隔
if ((e.Item.ItemIndex + 1) % 5 == 0 && (e.Item.ItemIndex + 1) < 15)
{
e.Item.Controls.Add(new LiteralControl("<hr class='separator' />"));
}
}
}
private DataTable GetTable()
{
var dt = new DataTable();
dt.Columns.Add("title", typeof(string));
for (int i = 1; i <= 15; i++)
dt.Rows.Add(dt.NewRow() { ["title"] = $"這是文章標題 {i}" });
return dt;
}
<style>
.item-list li { list-style:none; padding:8px; border-bottom:1px solid #eee; }
.item-list li:nth-child(5n) { border-bottom:2px solid #0a8fda; margin-bottom:10px; }
/* 或用偽元素插入分隔線 */
.item-list li:nth-child(5n)::after {
content:""; display:block; height:1px; background:#0a8fda; margin-top:10px;
}
</style>
<asp:Repeater ID="rptList" runat="server">
<HeaderTemplate><ul class="item-list"></HeaderTemplate>
<ItemTemplate>
<li><asp:Literal ID="ltlTitle" runat="server" /></li>
</ItemTemplate>
<FooterTemplate></ul></FooterTemplate>
</asp:Repeater>
| 維度 | 後端插入 LiteralControl | CSS :nth-child |
|---|---|---|
| 維護性 | 需修改 C# 代碼 | 僅改 CSS,職責分離 |
| 效能 | 增加伺服器端 Controls 集合操作 | 零伺服器負擔 |
| 彈性 | 可插入複雜伺服器控制項 | 僅限樣式/偽元素內容 |
| 相容性 | 所有瀏覽器 | IE9+ (現代專案無問題) |