Aug 29, 2010

Adding Gridview nested in Repeater in ASP.NET 2.0

Generally, we require nested structure of grid to display hierarchical data or Master Child data. Here it is done using gridview nested in repeater.

In aspx Page:


<asp:Repeater ID="rpt" runat="server" 
            onitemdatabound="rpt_ItemDataBound">
        <ItemTemplate>
            <asp:GridView ID="Grd" runat="server">            
            </asp:GridView>
        </ItemTemplate> 
    </asp:Repeater>   

In .CS Page:



protected void Page_Load(object sender, EventArgs e)
    {
  rpt.DataSource = GetData();
        rpt.DataBind();    
    }   

protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            GridView gv = (GridView)e.Item.FindControl("grd");
            if (gv != null)
            {
                DataRowView drv = (DataRowView)e.Item.DataItem;
                gv.DataSource = GetSubData(Convert.ToInt32(drv["ID"]));
                gv.DataBind();            
            }
        }
    }


private DataTable GetData()
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Name");
        dt.Columns.Add("Size");
        dt.Columns.Add("Enabled");
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = i.ToString();
                dr[1] = i.ToString() + "-Name-" + j.ToString();
                dr[2] = i.ToString() + "-Size-" + j.ToString();
                dr[3] = Convert.ToBoolean(i % 2);
                dt.Rows.Add(dr);
            }
        }
        return dt;
    }
    protected DataTable GetSubData(int ij)
    {

        DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("SubName");
        dt.Columns.Add("SubSize");
        dt.Columns.Add("Enabled");
        for (int j = 0; j < 3; j++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = ij.ToString();
            dr[1] = ij.ToString() + "-Name-" + j.ToString();
            dr[2] = ij.ToString() + "-Size-" + j.ToString();
            dr[3] = Convert.ToBoolean(ij % 2);
            dt.Rows.Add(dr);
        }

        return dt;
}

Hope, It Helps.