將 Nested-GridView 與 DataSource 繫結,例如 DataTable

  1. 巢狀 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>
  1. 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
    }
}
  1. 在父 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 後看起來像:

StackOverflow 文件