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>