Nested GridView in ASP.NET


This article explains how to use a GridView inside another GridView. Here in the first GridView there are three columns named as DepartmentId, DepartmentName and details. All data of DepartmentId and DepartmentName will be shown in the first GridView along with a details button. So when we will click the Details button then records related to the corresponding DepartmentName will be shown in the second GridView.

Table structure

We will create five tables.

Department table


Create 4 more tables as ComputerScience, Electronics, Electrical and Mechanical as below.



<%
@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    CellPadding="4" ForeColor="#663300" onrowcommand="GridView1_RowCommand" onrowcancelingedit="GridView1_RowCancelingEdit">
            <AlternatingRowStyle BackColor="#CCCC00" />
            <Columns>
                <asp:TemplateField HeaderText="Department_Id">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("DepartmentId") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("DepartmentId") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department_Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("DepartmentName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("DepartmentName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText = "Details">
               <ItemTemplate>
          <asp:Button ID ="btn_Show" Text="Details" runat= "server" CommandName= "Details" CommandArgument='<%#
            Container.DataItemIndex%>' />
          <asp:Button ID ="Cancel" Text="Cancel" runat= "server" CommandName= "Cancel" CommandArgument='<%#
            Container.DataItemIndex%>' Visible="false" / 
                     <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" CellPadding="4"
                       
ForeColor="#000000" GridLines="Both">
                 <AlternatingRowStyle BackColor="Yellow" />
                        <Columns>
                          <asp:BoundField DataField="Id" HeaderText= "Id" >
                           <
ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Name" HeaderText= "Name" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Address" HeaderText= "Address" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Branch" HeaderText= "Branch" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                          <asp:BoundField DataField="Phone" HeaderText= "Phone" >
                          <ItemStyle Width = "20%" />
                          </asp:BoundField>
                         </Columns>
                         <EditRowStyle BackColor="#7C6F57" />
             <
FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="Red" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
                        </asp:GridView>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <EditRowStyle BackColor="#7C6F57" />
            <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#CC6600" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#E3EAEB" />
            <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        </asp:GridView>
    </div>
    </form>
</body>
</
html>

using
System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page|
{
    string connStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlCommand com;
    SqlDataAdapter sqlda;
    DataSet ds;
    string str;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    protected void BindGrid()
    {
        SqlConnection con = new SqlConnection(connStr);
        con.Open();
        str = "select * from Department";
        com = new SqlCommand(str, con);
        sqlda = new SqlDataAdapter(com);
        con.Close();
        ds = new DataSet();
        sqlda.Fill(ds, "Department");
        GridView1.DataSource = ds;
        GridView1.DataMember = "Department";
        GridView1.DataBind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int rowindex = Convert.ToInt32(e.CommandArgument.ToString());
        GridView g2 = (GridView)GridView1.Rows[rowindex].FindControl("GridView2");
        Label lbl = (Label)GridView1.Rows[rowindex].FindControl("Label2");
        GridView1.Rows[rowindex].FindControl("Cancel").Visible = false;
        if (e.CommandName == "Details")
        {
            GridView1.Rows[rowindex].FindControl("Cancel").Visible = true;
            GridView1.Rows[rowindex].FindControl("btn_Show").Visible = false;
            SqlConnection con = new SqlConnection(connStr);
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter();
            DataSet ds = new DataSet();
 
            if (lbl.Text == "ComputerScience")
            {
                da.SelectCommand = new SqlCommand("Select * from ComputerScience", con);
                da.Fill(ds);
            }
            else if (lbl.Text == "Electronics")
            {
                da.SelectCommand = new SqlCommand("Select * from Electronics", con);
                da.Fill(ds);
            }
            else if (lbl.Text == "Electrical")
            {
                da.SelectCommand = new SqlCommand("Select * from Electrical", con);
                da.Fill(ds);
            }
            else
            {
 
                da.SelectCommand = new SqlCommand("Select * from Mechanical", con);
                da.Fill(ds);
            }
            g2.DataSource = ds;
            g2.DataBind();
            g2.Visible = true;
        }
        else
        {
            g2.Visible = false;
            GridView1.Rows[rowindex].FindControl("btn_Show").Visible = true;
        }
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
    }
}

Output :




Up Next
    Ebook Download
    View all
    Learn
    View all