常見需求:顯示主清單(如主管清單),每筆主記錄下再顯示其從屬明細(如該主管的行程)。本文示範使用 Repeater 做外層主資料,內嵌 GridView 顯示子資料,並透過 ItemDataBound 事件動態繫結,達成主從式資料呈現。
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table border="0" cellspacing="0" cellpadding="0" width="100%"><tr>
</HeaderTemplate>
<ItemTemplate>
<td class="list_table_in">
<span class="leaderTitle">
主管:<a href='/Leader/Detail.aspx?loginName=<%# Eval("LoginName") %>'><%# Eval("UserName") %></a>
</span>
<asp:GridView ID="gv_InRep" runat="server" AutoGenerateColumns="False"
AllowSorting="True" AllowPaging="True" CssClass="tasklisttbl" Width="100%"
OnRowCreated="GV_DoneList_RowCreated" OnSorting="GV_DoneList_Sorting"
OnRowDataBound="GV_DoneList_RowDataBound">
<AlternatingRowStyle BackColor="#FDFEFF" />
<HeaderStyle HorizontalAlign="Center" ForeColor="Black" Height="20" />
<RowStyle HorizontalAlign="Center" Height="26px" />
<Columns>
<asp:BoundField HeaderText="日期" DataField="Date" SortExpression="Date" ItemStyle-Width="15%" />
<asp:BoundField HeaderText="時間" DataField="Time" SortExpression="Time" ItemStyle-Width="11%" />
<asp:BoundField HeaderText="工作安排" DataField="WorkPlan" SortExpression="WorkPlan" ItemStyle-Width="11%" />
<asp:BoundField HeaderText="地點" DataField="Place" SortExpression="Place" ItemStyle-Width="11%" />
</Columns>
<PagerTemplate></PagerTemplate>
</asp:GridView>
<asp:Literal ID="Literal1" runat="server" Text='<%# Eval("Flag") %>' />
</td>
</ItemTemplate>
<FooterTemplate></tr></table></FooterTemplate>
</asp:Repeater>
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// 1. 找到內層 GridView
var gv = (GridView)e.Item.FindControl("gv_InRep");
// 2. 取得目前 Repeater 繫結的資料項
var leader = (Leader)e.Item.DataItem;
string loginName = leader.LoginName; // 當作查詢條件
// 3. 設定排序狀態(視需求)
SetSorting();
// 4. 依條件查詢子資料並繫結
gv.DataSource = GetScheduleData(loginName); // 自訂方法回傳 DataTable/DataView/List
gv.DataBind();
}
}
catch (Exception ex)
{
// 記錄錯誤日誌
LogException(ex, "Repeater 巢狀 GridView 繫結失敗");
}
}
ItemDataBound 內尋找內層控件,其他事件找不到。DataRelation 或 LINQ 分組在記憶體關聯。ListView + GroupTemplate 替代(ASP.NET 3.5+)。foreach 迴圈中渲染巢狀 table,零 ViewState、零控件生命週期負擔。Repeater 巢狀 GridView 是 WebForm 時代經典的主從資料呈現模式。掌握 ItemDataBound 動態繫結精髓,並注意 N+1 查詢效能陷阱,即能在舊專案維護中游刃有餘。新專案建議採用前後端分離架構,徹底解決伺服器端控件巢狀複雜度問題。