Tuesday, August 27, 2013

Nested Gridview Example in Asp.net OR Gridview inside Gridview in asp.net

Introduction: In this article I have explain how we can use Gridview inside Gridview in asp.net.
Nested Gridview

Description:
In the last article i have explained How to use Checkbox control inside Gridview in asp.net and How to use Join in LINQ Query.
To explain example  I have create 3 Table COUNTRY_DETAIL
ID
int
COUNTRY
varchar(50)
CAPITAL
varchar(50)

STATE_DETAIL
ID
int
STATE_NAME
varchar(50)
POPULATION
bigint
COUNTRY_ID_FK
int

STATE_POPULATION
ID
int
MALE
bigint
FEMALE
bigint
STATE_ID_FK
int


Add a new webform to project. Drag and drop the controls from Toolbox and desgin the .aspx page as mention below:
<table align="center"><tr><td>
        <asp:GridView ID="gvcountry" runat="server" AutoGenerateColumns="False" HeaderStyle-BackColor="#3DB8E4" HeaderStyle-ForeColor="White"
            DataSourceID="SqlDataSource1" onrowdatabound="gvcountry_RowDataBound"
            DataKeyNames="ID" EmptyDataText="No records found">
            <RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
        <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <img alt = "" style="cursor: pointer" src="images/plus.png" />
                 <div Style="display: none">
                    <asp:GridView ID="gvstate" runat="server" HeaderStyle-BackColor="#3B5998" HeaderStyle-ForeColor="White" AutoGenerateColumns="false" EmptyDataText="No records found" DataKeyNames="ID" CssClass = "ChildGrid" onrowdatabound="gvstate_RowDataBound">                   
                       <RowStyle BackColor="#E2FFFF" />
<AlternatingRowStyle BackColor="White" />
                        <Columns>
                            <asp:TemplateField>
                            <ItemTemplate>
                             <img alt = "" style="cursor: pointer" src="images/plus.png" />
                              <div Style="display: none">
                              <asp:GridView ID="gvpopulation"  HeaderStyle-BackColor="Goldenrod" HeaderStyle-ForeColor="White" DataKeyNames="ID" runat="server" AutoGenerateColumns="false" EmptyDataText="No records found">
                              <Columns>
                              <asp:BoundField ItemStyle-Width="150px" DataField="MALE" HeaderText="Male" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="FEMALE" HeaderText="Female" />
                              </Columns>
                               <EmptyDataRowStyle Width = "550px" ForeColor="Red" Font-Bold="true"
   HorizontalAlign = "Center"/>
                              </asp:GridView>
                              </div>
                            </ItemTemplate>                          
                            </asp:TemplateField>
                             <asp:BoundField ItemStyle-Width="150px" DataField="STATE_NAME" HeaderText="State Name" />
                            <asp:BoundField ItemStyle-Width="150px" DataField="POPULATION" HeaderText="Population" />
                        </Columns>
                          <EmptyDataRowStyle Width = "550px" ForeColor="Red" Font-Bold="true"
   HorizontalAlign = "Center" />
                    </asp:GridView>
                    </div>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField ItemStyle-Width="150px" DataField="COUNTRY" HeaderText="Country Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="CAPITAL" HeaderText="Capital" />    
    </Columns>
     <EmptyDataRowStyle Width = "550px" ForeColor="Red" Font-Bold="true"
   HorizontalAlign = "Center"/>
        </asp:GridView></td></tr></table>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:TEST_APPLICATIONConnectionString %>"
            SelectCommand="SELECT * FROM [COUNTRY_DETAIL]"></asp:SqlDataSource>

Add the below given Javascript in between Head Tag:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>

Note: Please do not forget to add ConnectionString in web.config file:
<connectionStrings>
    <add name="con" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True" /> 


  </connectionStrings>

After that on .aspx.cs page write the below given code:
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
//Bind STATE_DETAIL Table to State Gridview on Country RowDataBound Event
    protected void gvcountry_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int id = Convert.ToInt32(gvcountry.DataKeys[e.Row.RowIndex].Value.ToString());
            GridView gvstatechild = (GridView)e.Row.FindControl("gvstate");
            SqlDataAdapter adp = new SqlDataAdapter("Select * from STATE_DETAIL WHERE C_ID_FK="+id, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            gvstatechild.DataSource = dt;
            gvstatechild.DataBind();          
          
        }
    }
    // Bind STATE_POPULATION Table to Population Gridview on State RowDataBound Event
    protected void gvstate_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            GridView gvstate = (GridView)sender;
            int id = Convert.ToInt32(gvstate.DataKeys[e.Row.RowIndex].Value.ToString());
            GridView gvchild = (GridView)e.Row.FindControl("gvpopulation");
            SqlDataAdapter adp = new SqlDataAdapter("Select * from STATE_POPULATION where STATE_ID_FK=" + id, con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
             gvchild.DataSource = dt;
            gvchild.DataBind();
        }
    }

In VB (.aspx.vb)
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("Connection").ToString())
    Protected Sub gvcountry_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvcountry.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim id As Integer = Convert.ToInt32(gvcountry.DataKeys(e.Row.RowIndex).Value.ToString())
            Dim gvstatechild As GridView = DirectCast(e.Row.FindControl("gvstate"), GridView)
            Dim adp As New SqlDataAdapter("Select * from STATE_DETAIL WHERE C_ID_FK=" & id, con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            gvstatechild.DataSource = dt

            gvstatechild.DataBind()
        End If
    End Sub
    Protected Sub gvstate_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim gvstate As GridView = DirectCast(sender, GridView)
            Dim id As Integer = Convert.ToInt32(gvstate.DataKeys(e.Row.RowIndex).Value.ToString())
            Dim gvchild As GridView = DirectCast(e.Row.FindControl("gvpopulation"), GridView)
            Dim adp As New SqlDataAdapter("Select * from STATE_POPULATION where STATE_ID_FK=" & id, con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            gvchild.DataSource = dt
            gvchild.DataBind()
        End If
    End Sub

Bulid and run the project.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment