ASP.NET GridView 本身不支持嵌套,因為它是一個用于顯示數據集的控件。但是,您可以通過以下方法實現類似嵌套的效果:
示例:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<h3><%# Eval("ParentName") %></h3>
<asp:GridView ID="NestedGridView" runat="server" AutoGenerateColumns="false" DataSource='<%# Eval("Children") %>'>
<Columns>
<asp:BoundField DataField="ChildName" HeaderText="Child Name" />
<asp:BoundField DataField="ChildAge" HeaderText="Child Age" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
示例:
public class NestedGridView : GridView
{
protected override void OnDataBound(EventArgs e)
{
base.OnDataBound(e);
if (DataSource is IList && DataSource is IList<NestedData>)
{
foreach (var item in DataSource as IList<NestedData>)
{
var nestedGridView = new GridView();
nestedGridView.DataSource = item.Children;
nestedGridView.AutoGenerateColumns = false;
nestedGridView.DataBind();
// Add nestedGridView to the parent GridView's ItemTemplate or EditItemTemplate
}
}
}
}
public class NestedData
{
public string ParentName { get; set; }
public IList<ChildData> Children { get; set; }
}
public class ChildData
{
public string ChildName { get; set; }
public int ChildAge { get; set; }
}
然后在 ASPX 頁面中使用自定義控件:
<custom:NestedGridView ID="NestedGridView1" runat="server">
</custom:NestedGridView>