How to Create a Second Level GridView in ASP.NET

In this article you will see how to create a second level GridView in ASP.NET.



This code example includes:

  1. Multiple Gridviews (a GridView within a GridView) 2nd level Gridview.
  2. Sorting in Gridview.
  3. Custom paging functionality.

Step 1: Your .aspx page is like:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="testSubGrid._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>Sub Grid By Jayendrasinh Gohil</title>
    <style type="text/css">
        .gv_city_mode2
        {
            background-color: Aqua;
        }
    </style>  
</head>
<
body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <table width="100%">
            <tr>
                <td>
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                        <ContentTemplate>
                            <asp:GridView ID="gv_city" runat="server" AutoGenerateColumns="False" AllowSorting="True"
                                OnSorting="gv_city_Sorting" OnRowDataBound="gv_city_RowDataBound" OnRowCommand="gv_city_RowCommand">
                                <Columns>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <asp:ImageButton ID="btnShow" runat="server" ImageUrl="~/Image/Plus.gif" AlternateText="Expand"
                                                CommandName="Show" CommandArgument='<%# ((GridViewRow)Container).RowIndex %>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="City ID" SortExpression="cityid">
                                        <ItemTemplate>
                                            <asp:Label ID="lbl_cityid" runat="server" Text='<%#Eval("cityid")%>'></asp:Label>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="City Name" SortExpression="cityname">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txt_cityname" runat="server" Text='<%#Eval("cityname")
>'></asp:TextBox>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField>
                                        <ItemTemplate>
                                            <tr>
                                                <td colspan="4">
                                                    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"
AutoGenerateDeleteButton="False"
                                                        AutoGenerateEditButton="False">
                                                        <Columns>
                                                            <asp:BoundField DataField="std_name" HeaderText="Student Name" SortExpression="std_name">
                                                                <ItemStyle Width="20%" />
                                                            </asp:BoundField>
                                                        </Columns>
                                                    </asp:GridView>
                                                </td>
                                            </tr>
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                </Columns>
                                <PagerTemplate>
                                    <asp:Button ID="btnprev" runat="server" Text="<< Previous" CommandName="Previous"
                                        OnClick="ChangePage" />
                                    <asp:Button ID="btnnext" runat="server" Text="Next >>" CommandName="Next" OnClick="ChangePage" />
                                    <asp:Label ID="lblCurrentPage" runat="server" Text=""></asp:Label>
                                </PagerTemplate>
                            </asp:GridView>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</
html>

Step 2 : Your .cs page is like:

using System;
using System.Collections;
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 DAL;
 
namespace testSubGrid
{
 
    public partial class _Default : System.Web.UI.Page
    {
        string _connectionstring = ConfigurationManager.ConnectionStrings["connection"].ToString();
        DataAccessblock dblock = new DataAccessblock();
        DataTable dt = new DataTable();
        int currentpageindex = 0;
        int Totalnumberofpage = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGridView();
            }
        }
 
        private void BindGridView()
        {
            dt = dblock.GetCityinfo(this._connectionstring);
            if (dt != null && dt.Rows.Count > 0)
            {
                gv_city.AllowPaging = true;
                gv_city.PageSize = 3;
                if (ViewState["currentpageindex"] != null)
                {
                    currentpageindex = Convert.ToInt32(ViewState["currentpageindex"]);
                }
                gv_city.PageIndex = currentpageindex;
                gv_city.DataSource = dt;
                gv_city.DataBind();
                Totalnumberofpage = gv_city.PageCount;
                ViewState["currentpageindex"] = currentpageindex;
                ViewState["Totalnumberofpage"] = Totalnumberofpage;
            }
        }       
 
        protected void gv_city_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Pager)
            {
                if (ViewState["currentpageindex"] != null)
                {
                    GridViewRow PagerRow = gv_city.BottomPagerRow;
                    Label lblpage = (Label)PagerRow.Cells[0].FindControl("lblCurrentPage");
                    lblpage.Text = "Page : " + Convert.ToInt32(ViewState["currentpageindex"]).ToString() + " " + "of " +
ViewState["Totalnumberofpage"].ToString();
                }
            }
            else if (e.Row.RowType == DataControlRowType.DataRow)
            {                              
                int mode = e.Row.RowIndex % 2;
                if (mode == 0)
                {
                    e.Row.CssClass = "gv_city_mode2";
                }
            }
 
        }
 
        protected void gv_city_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Show")
            {
                int RowIndex = Convert.ToInt32((e.CommandArgument).ToString()
;                                              
                ImageButton btn = (ImageButton)gv_city.Rows[RowIndex].FindControl("btnShow");
                if (btn.AlternateText == "Expand")
                {
                    btn.ImageUrl = "~/Image/Minus.gif";
                    GridView gv = (GridView)gv_city.Rows[RowIndex].FindControl("GridView2");
                    int id = int.Parse(((Label)gv_city.Rows[RowIndex].FindControl("lbl_cityid")).Text);
                    DataTable dt = dblock.GetStudentinfo(this._connectionstring, id);
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        gv.DataSource = dt;
                        gv.DataBind();
                        btn.AlternateText = "Collapse";
                    }
                }
                else if (btn.AlternateText == "Collapse")
                {
                    btn.ImageUrl = "~/Image/Plus.gif";
                    GridView gv = (GridView)gv_city.Rows[RowIndex].FindControl("GridView2");
                    long id = long.Parse(e.CommandArgument.ToString());
                    gv.DataSource = null;
                    gv.DataBind();
                    btn.AlternateText = "Expand";
                }
            }
        }

        protected void gv_city_Sorting(object sender, GridViewSortEventArgs e)
        {

            if (ViewState["SortDirection"] != null)
            {
 
                if (ViewState["SortDirection"].ToString() == "Ascending")
                {
                    e.SortDirection = SortDirection.Descending;
                }
                else if (ViewState["SortDirection"].ToString() == "Descending")
                {
                    e.SortDirection = SortDirection.Ascending;
                }
            }
            dt = dblock.GetCityinfo(this._connectionstring);
            if (dt != null)
            {
                DataView dataView = new DataView(dt);
                dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);

                gv_city.DataSource = dataView;
                gv_city.DataBind();
            }
            ViewState["SortDirection"] = e.SortDirection;
        }

        private string ConvertSortDirectionToSql(SortDirection sortDirection)
        {
            string newSortDirection = String.Empty;

            switch (sortDirection)
            {
                case SortDirection.Ascending:
                    newSortDirection = "ASC";
                    break;

                case SortDirection.Descending:
                    newSortDirection = "DESC";
                    break;
            }

            return newSortDirection;
        }

        protected void ChangePage(object sender, EventArgs e)
        {

            string CommandName = ((System.Web.UI.WebControls.Button)(sender)).CommandName;
            switch (CommandName)
            {
                case "Previous":
                    if (ViewState["currentpageindex"] != null)
                    {
                        if (Convert.ToInt32(ViewState["currentpageindex"]) != 0)
                        {
                            currentpageindex = Convert.ToInt32(ViewState["currentpageindex"]) - 1;
                            ViewState["currentpageindex"] = currentpageindex;
                        }
                    }
                    else
                    {
                        if (currentpageindex != 0)
                        {
                            currentpageindex = currentpageindex - 1;
                            ViewState["currentpageindex"] = currentpageindex;
                        }
                    }
                    break;
 
                case "Next":
                    if ((ViewState["currentpageindex"] != null) && (ViewState["Totalnumberofpage"] != null))
                    {
                        if (Convert.ToInt32(ViewState["currentpageindex"]) < (Convert.ToInt32(ViewState["Totalnumberofpage"]) - 1))
                        {
                            currentpageindex = Convert.ToInt32(ViewState["currentpageindex"]) + 1;
                            ViewState["currentpageindex"] = currentpageindex;
                        }
                    }
                    else
                    {
                        if (currentpageindex != Totalnumberofpage)
                        {
                            currentpageindex = currentpageindex + 1;
                            ViewState["currentpageindex"] = currentpageindex;
                        }
                    }
                    break;
            }
            GridViewRow pagerRow = gv_city.BottomPagerRow;
            Label lblpage = (Label)pagerRow.Cells[0].FindControl("lblCurrentPage");
            lblpage.Text = "Page : " + Convert.ToInt32(ViewState["currentpageindex"]).ToString() + " " + "of " + ViewState["Totalnumberofpage"].ToString();
            BindGridView();
        }
 
    }
}