将 Nested-GridView 与 DataSource 绑定,例如 DataTable
- 嵌套 GridView 的设计( HTML 代码 ):
<asp:GridView ID="gvParent" runat="server" AutoGenerateColumns="false" OnRowDataBound="gvParent_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Parent Column">
<ItemTemplate>
<asp:Label ID="lblParent" runat="server" Text='<% #Bind("parent") %>'></asp:Label>
<asp:GridView ID="gvChild" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="Child Column">
<ItemTemplate>
<asp:Label ID="lblChild" runat="server" Text='<% #Bind("child") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
- 在
Page_Load
事件中绑定父 GridView:
DataTable cgv = new DataTable(); // define temporary a datatable for accessing in rowdatabound event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Create a datatable as a DataSource of your GridViews
DataTable dtParent = new DataTable(); // parent gridview datasource
DataTable dtChild = new DataTable(); // child gridview datasource
// Add column(s) in datatables and their names and data types
dtParent.Columns.Add(new DataColumn("parent", typeof(string))); // parent column
dtChild.Columns.Add(new DataColumn("child", typeof(string))); // child column
// Add two records in parent datatable
for (int i = 0; i < 2; i++)
dtParent.Rows.Add("Parent" + i);
// Add three records in child datatable
for (int i = 0; i < 3; i++)
dtChild.Rows.Add("Child" + i);
cgv = dtChild; // set child datatable to temprary datatable
gvParent.DataSource = dtParent; // set your parent datatable to parent gridview as datasource
gvParent.DataBind(); // bind the gridview with datasource
}
}
- 在父 GridView 的
OrRowDataBound
事件中绑定 Child GridView。
protected void gvParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find all child gridviews from parent
GridView gvChild = ((GridView)e.Row.FindControl("gvChild"));
gvChild.DataSource = cgv; // set your child datatable to parent gridview as datasource
gvChild.DataBind(); // bind the gridview with datasource
}
}
绑定 Nested-GridView 后看起来像: