外層 Repeater 繫結分類資料,內層 Repeater 於 ItemDataBound 事件中依分類 ID 篩選產品資料並繫結,實現主從關係顯示。
private DataTable dtCategory, dtProduct;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dtCategory = GetCategoryTable();
dtProduct = GetProductTable();
rptCategory.DataSource = dtCategory;
rptCategory.DataBind();
}
}
private DataTable GetCategoryTable()
{
var dt = new DataTable();
dt.Columns.Add("CategoryId", typeof(int));
dt.Columns.Add("CategoryTitle", typeof(string));
for (int i = 1; i <= 3; i++)
dt.Rows.Add(i, $"分類名字 {i}");
return dt;
}
private DataTable GetProductTable()
{
var dt = new DataTable();
dt.Columns.Add("ProductTitle", typeof(string));
dt.Columns.Add("CategoryId", typeof(int));
for (int i = 1; i <= 9; i++)
{
dt.Rows.Add($"產品名字 {i}", i > 6 ? 3 : (i > 3 ? 2 : 1));
}
return dt;
}
private DataTable GetProductsByCategory(int catId)
{
var dv = dtProduct.DefaultView;
dv.RowFilter = $"CategoryId = {catId}";
return dv.ToTable();
}
protected void rptCategory_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var drv = (DataRowView)e.Item.DataItem;
int catId = Convert.ToInt32(drv["CategoryId"]);
((Literal)e.Item.FindControl("ltlCatTitle")).Text = drv["CategoryTitle"].ToString();
var rptProduct = (Repeater)e.Item.FindControl("rptProduct");
rptProduct.DataSource = GetProductsByCategory(catId);
rptProduct.DataBind();
}
}
protected void rptProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var drv = (DataRowView)e.Item.DataItem;
((Literal)e.Item.FindControl("ltlProdTitle")).Text = drv["ProductTitle"].ToString();
}
}
<asp:Repeater ID="rptCategory" runat="server" OnItemDataBound="rptCategory_ItemDataBound">
<ItemTemplate>
<div class="category-box">
<div class="cat-title"><asp:Literal ID="ltlCatTitle" runat="server" /></div>
<ul class="product-list">
<asp:Repeater ID="rptProduct" runat="server" OnItemDataBound="rptProduct_ItemDataBound">
<ItemTemplate>
<li><asp:Literal ID="ltlProdTitle" runat="server" /></li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
RowFilter 每次建立 DataView 開銷較大。建議:Dictionary<int, List<Product>> 分組,ItemDataBound 直接 dict[catId] 取得列表。LINQ to DataTable:dtProduct.AsEnumerable().Where(r => r.Field<int>("CategoryId") == catId)。ListView + GroupTemplate 或前端框架 (Vue/React) 以 AJAX 分批載入子項。