SIGN UP MEMBER LOGIN:    
ARTICLE

Nested GridView in ASP.NET

Posted by Satyapriya Nayak Articles | ASP.NET Programming January 12, 2012
This article explains how to use a GridView inside another GridView.
Reader Level:

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 :




Login to add your contents and source code to this article
share this article :
post comment
 

Thanks

Posted by Satyapriya Nayak Jan 13, 2012

Hi Satyapriya. You have presented you article nicely. Thanks for sharing it.

Posted by Maria Johnson Jan 13, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor