Click here to Skip to main content
Click here to Skip to main content

Multilevel Nested Gridview in ASP.NET

, 2 Jul 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Display data in Multi nested gridview using C# in ASP.NET

Click to enlarge image

Introduction

This project is used to display data in multilevel nested gridview using C#. It is useful to show the data which has relation between multiple data tables.This can solve the problem of showing the people or things coming under single category.

Background

Displaying data in multiple windows or in popup windows is fine, but when we try to find the relation between first thing to last thing is difficult, so I am giving this solution to show data which has relation between them in a single page under the same category.

Basic Knowledge

Before using this code, the developer must know Gridview, Gridview events, Data table, cloning data table, and a little bit of knowledge on CSS and Jquery.

Header

Create a web project in Visual Studio. Now add the following CSS in <header></header> section.

 <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
            
        }
        .Grid td
        {
            background-color: #A1DCF2;
            color: black;
            font-size: 10pt;
            line-height:200%
        }
        .Grid th
        {
            background-color: #3AC0F2;
            color: White;
            font-size: 10pt;
            line-height:200%
        }
        .ChildGrid td
        {
            background-color: #eee !important;
            color: black;
            font-size: 10pt;
            line-height:200%
        }
        .ChildGrid th
        {
            background-color: #6C6C6C !important;
            color: White;
            font-size: 10pt;
            line-height:200%
        }
    </style>

The above CSS is used to show Parent gridview header color, child grid header color and font size, style and color.

Now add the following Jquery on header for expand functionality on grid.

<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>

The above Jquery is used to expand grid by clicking on image buttons. These images are available on images folder in Zipcode file.

Now <header> section will look like this:

<head runat="server">
    <title>Multi nested gridview</title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
            
        }
        .Grid td
        {
            background-color: #A1DCF2;
            color: black;
            font-size: 10pt;
            line-height:200%
        }
        .Grid th
        {
            background-color: #3AC0F2;
            color: White;
            font-size: 10pt;
            line-height:200%
        }
        .ChildGrid td
        {
            background-color: #eee !important;
            color: black;
            font-size: 10pt;
            line-height:200%
        }
        .ChildGrid th
        {
            background-color: #6C6C6C !important;
            color: White;
            font-size: 10pt;
            line-height:200%
        }
    </style>
    <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>
</head>

Body

Here, we should concentrate on three things:

  1. Data Grid
  2. Panel
  3. Image control

Now add a parent Gridview control within the form.

Parent Grid

<asp:GridView ID="universityGrid" 
runat="server" AutoGenerateColumns="False" 
CssClass="Grid"></asp:GridView>

Add image and panel controls in <ItemTemplate> of Grid.

<asp:Image ID="Image1" runat="server" 
style="cursor:pointer" ImageUrl="~/images/plus.png"/>
<asp:Panel ID="pnlunivesity" runat="server" Style="display: none">

Image control is used to expand the grid and panel is used to display child grid within parent grid.

Parent gridview looks like this at the initial stage.

<asp:GridView ID="universityGrid" runat="server" 
AutoGenerateColumns="False"CssClass="Grid"
OnRowDataBound="universityGrid_RowDataBound" DataKeyNames="UnivercityCode" >
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                       
                         <asp:Image ID="Image1" runat="server" 
                         style="cursor: pointer" ImageUrl="~/images/plus.png"/>
                        <asp:Panel ID="pnlunivesity" runat="server" Style="display: none">
                    </ItemTemplate>
                    </asp:TemplateField>
                <asp:BoundField ItemStyle-Width="150px" DataField="UnivercityCode"
                                                     HeaderText="Univercity Code">
                <ItemStyle Width="150px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField ItemStyle-Width="150px" DataField="UniversityName"
                                                    HeaderText="University Name">
                <ItemStyle Width="150px"></ItemStyle>
                </asp:BoundField>
            </Columns>
        </asp:GridView>

Multilevel Nested Grid 

Add child gridview within parent gridview, here I have added three child grids within parent grid.

Final grid will look like this:

<asp:GridView ID="universityGrid" runat="server" 
AutoGenerateColumns="False" CssClass="Grid" 
OnRowDataBound="universityGrid_RowDataBound" DataKeyNames="UnivercityCode" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
style="cursor: pointer" ImageUrl="~/images/plus.png"/>
<asp:Panel ID="pnlunivesity" runat="server" Style="display: none">
<asp:GridView ID="clgGrid" runat="server" 
AutoGenerateColumns="false"  CssClass="ChildGrid" 
OnRowDataBound="clgGrid_RowDataBound" DataKeyNames="CollegeCode">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server"style="cursor: 
pointer" ImageUrl="~/images/plus.png"/>
<asp:Panel ID="pnlcollege" runat="server" 
Style="display: none">
<asp:GridView ID="branchGrid" runat="server" 
AutoGenerateColumns="false" CssClass="ChildGrid" 
OnRowDataBound="branchGrid_RowDataBound"  DataKeyNames="BranchCode" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="Image1" runat="server"style="cursor: pointer" 
ImageUrl="~/images/plus.png"/>
<asp:Panel ID="pnlbranch" runat="server" Style="display: none">
<asp:GridView ID="studentGrid" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="StudentID" HeaderText="Student ID"/>
<asp:BoundField ItemStyle-Width="150px" DataField="StudentName" HeaderText="Student Name"/>
<asp:BoundField ItemStyle-Width="150px" DataField="BranchName" HeaderText="Branch Name" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="BranchCode" HeaderText="Branch Code"/>
<asp:BoundField ItemStyle-Width="150px" DataField="BranchName" HeaderText="Branch Name" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="CollegeCode" HeaderText="College Code"/>
<asp:BoundField ItemStyle-Width="150px" DataField="CollegeName" HeaderText="College Name"/>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="UnivercityCode" HeaderText="Univercity Code">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
<asp:BoundField ItemStyle-Width="150px" DataField="UniversityName" HeaderText="University Name">
<ItemStyle Width="150px"></ItemStyle>
</asp:BoundField>
</Columns>
</asp:GridView>

Code Behind: C#

Sample data in multiple datatables

Create four data tables and these four data tables have relation between them like student code related to branchcode, branchcode is related to college code and college code has the relation with universitycode.

private static DataTable Getdata()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("UnivercityCode");
            dt.Columns.Add("UniversityName");
            dt.Rows.Add("UNS111", "Nagarjuna University");
            dt.Rows.Add("UNS222", "Andhra University");
            dt.Rows.Add("UNS333", "JNTUniversity");
            return dt;
        }
        private DataTable Getdata1
        {
            get
            {
dt.Columns.Add("CollegeCode");
dt.Columns.Add("CollegeName");
dt.Columns.Add("UnivercityCode");
dt.Rows.Add("CLG111", "A.B.M. Degree College", "UNS111");
dt.Rows.Add("CLG222", "Raghu Institute of Technology", "UNS222");
dt.Rows.Add("CLG333", "Annie Besant College of Education", "UNS111");
dt.Rows.Add("CLG444", "NOVA'S INSTITUTE OF TECHNOLOGY FOR WOMEN", "UNS333");
dt.Rows.Add("CLG555", "Sankethika Vidya Parishad Engineering College", "UNS222");
dt.Rows.Add("CLG666", "ADARSA COLLEGE OF PHARMACY", "UNS333");
dt.Rows.Add("CLG777", "BA&KR College", "UNS111");
dt.Rows.Add("CLG888", "Anil Neerukonda Institute Of Technology & Science", "UNS222");
dt.Rows.Add("CLG999", "Bharathi Degree College", "UNS111");
dt.Rows.Add("CLG11", "AVANTHI INSTITUTE OF ENGG. & TECHNOLOGY", "UNS333");
dt.Rows.Add("CLG22", "V.S.M. College of Engineering", "UNS222");
dt.Rows.Add("CLG33", "AL-AMAN COLLEGE OF ENGINEERING", "UNS333");

    return dt;
            }
        }
        private DataTable Getdata2
        {
            get
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("CollegeCode");
                dt.Columns.Add("BranchCode");
                dt.Columns.Add("BranchName");
                dt.Rows.Add("CLG111", "BNC111", "ECE");
                dt.Rows.Add("CLG222", "BNC222", "CSC");
                dt.Rows.Add("CLG333", "BNC333", "EEE");
                dt.Rows.Add("CLG444", "BNC444", "CSC");
                dt.Rows.Add("CLG555", "BNC555", "EEE");
                dt.Rows.Add("CLG666", "BNC666", "ECE");
                dt.Rows.Add("CLG777", "BNC777", "EEE");
                dt.Rows.Add("CLG888", "BNC888", "CSC");
                dt.Rows.Add("CLG999", "BNC999", "ECE");
                dt.Rows.Add("CLG11",  "BNC11",  "CSC");
                dt.Rows.Add("CLG22",  "BNC22",  "EEE");
                dt.Rows.Add("CLG33",  "BNC33",  "ECE");
                return dt;
            }
        }
        private DataTable Getdata3
        {
            get
            {                 
                DataTable dt = new DataTable();
                dt.Columns.Add("BranchCode");
                dt.Columns.Add("StudentID");
                dt.Columns.Add("StudentName");
                dt.Columns.Add("BranchName");
                dt.Rows.Add("BNC333","SID11","Chandrakirthi", "EEE");
                dt.Rows.Add("BNC111", "SID12", "Fadee", "ECE");
                dt.Rows.Add("BNC222", "SID13", "Paawan", "CSC");
                dt.Rows.Add("BNC333", "SID14", "Kaamla", "EEE");
                dt.Rows.Add("BNC111", "SID15", "Chandrasen", "ECE");
                dt.Rows.Add("BNC222", "SID16", "Kabira", "CSC");
                dt.Rows.Add("BNC333", "SID21", "Gaerwn", "EEE");
                dt.Rows.Add("BNC111", "SID22", "Gagana", "ECE");
                dt.Rows.Add("BNC111", "SID23", "Paddy", "ECE");
                dt.Rows.Add("BNC333", "SID24", "Gaganasindhu", "EEE");
                dt.Rows.Add("BNC222", "SID25", "Earlene", "CSC");
                dt.Rows.Add("BNC111", "SID26", "Edalene", "ECE");
                dt.Rows.Add("BNC444", "SID31", "Chandrakirthi", "CSC");
                dt.Rows.Add("BNC666", "SID32", "Fadee", "ECE");
                dt.Rows.Add("BNC555", "SID33", "Paawan", "EEE");
                dt.Rows.Add("BNC999", "SID34", "Kaamla", "ECE");
                dt.Rows.Add("BNC888", "SID35", "Chandrasen", "CSC");
                dt.Rows.Add("BNC777", "SID36", "Kabira", "EEE");
                dt.Rows.Add("BNC333", "SID41", "Gaerwn", "EEE");
                dt.Rows.Add("BNC555", "SID42", "Gagana", "EEE");
                dt.Rows.Add("BNC11", "SID43", "Paddy", "CSC");
                dt.Rows.Add("BNC33", "SID44", "Gaganasindhu", "ECE");
                dt.Rows.Add("BNC22", "SID45", "Earlene", "EEE");
                dt.Rows.Add("BNC444", "SID46", "Edalene", "CSC");
                return dt;
            }
        }

Show data in Grid

Go to universitygridview events and click on Onrowdatabound event. Add the following code in code block:

Parent Grid

protected void universityGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //datakey is assigned on grid control as DataKeyNames="UnivercityCode"
                string id1 = universityGrid.DataKeys[e.Row.RowIndex].Value.ToString();
                //data table cloing
                DataTable dt = Getdata1.Clone();
                //get data from datatable and assign into datarow
                foreach (DataRow dr in Getdata1.Rows)
                {
                    
                    if (dr[2].ToString() == id1)
                    {
                        //create new datarow
                        DataRow newdr = dt.NewRow();
                        // add data into newly created datarows
                        newdr[0] = dr[0];
                        newdr[1] = dr[1];
                        newdr[2] = dr[2];
                        //adding row data to datatable
                        dt.Rows.Add(newdr);
                    }
                }
                //find child grid control with in grid
                GridView grdview = e.Row.FindControl("clgGrid") as GridView;
                // assign datatable to grid
                grdview.DataSource = dt;
                //bind data to grid
                grdview.DataBind();
            }
        }

Child Grid

Go to clggridview events and click on Onrowdatabound event, add the following code in code block:

protected void clgGrid_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                try
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        GridView grid = (GridView)sender;
                      //data key is assigned on grid control as DataKeyNames="CollegeCode"
                      string id1 = grid.DataKeys[e.Row.RowIndex].Value.ToString();
                        DataTable dt = Getdata2.Clone();
                        foreach (DataRow dr in Getdata2.Rows)
                        {
                            if (dr[0].ToString() == id1)
                            {
                                DataRow newdr = dt.NewRow();
                                newdr[0] = dr[0];
                                newdr[1] = dr[1];
                                newdr[2] = dr[2];
                                
                                dt.Rows.Add(newdr);
                            }
                        }
                        GridView grdview = e.Row.FindControl("branchGrid") as GridView;
                        grdview.DataSource = dt;
                        grdview.DataBind();
                    }
                }
                catch { }
            }

Inner Child Grid

Go to branchgridview events and click on Onrowdatabound event. Add the following code in code block:

protected void branchGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    GridView grid = (GridView)sender;
                    string id1 = grid.DataKeys[e.Row.RowIndex].Value.ToString();
                    DataTable dt = Getdata3.Clone();
                    foreach (DataRow dr in Getdata3.Rows)
                    {
                        if (dr[0].ToString() == id1)
                        {
                            DataRow newdr = dt.NewRow();
                            newdr[0] = dr[0];
                            newdr[1] = dr[1];
                            newdr[2] = dr[2];
                            newdr[3] = dr[3];
                            dt.Rows.Add(newdr);
                        }
                    }
                    GridView grdview = e.Row.FindControl("studentGrid") as GridView;
                    grdview.DataSource = dt;
                    grdview.DataBind();
                }
            }
            catch { }
        }

Page Load:

Call Parent grid in Page Load

Now assign Getdata data table to parent grid (universitygridview) in page load like this:

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

Points of Interest

We will learn about gridview control in ASP.NET while using this tip.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Chakravarthi Elchuri
Software Developer
India India
Having good experience of developing code for CTI, Scanner, Cammera, Interactive maps for IRP(International Registration Plan)integration and 311 service request maps using different Geocoding API providers.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberMember 1027731520-Nov-14 11:30 
SuggestionHeading Formatting PinprotectorTadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)3-Jul-14 2:17 
SuggestionScreenshots please! PinmemberJaredThirsk2-Jul-14 14:20 
GeneralRe: Screenshots please! Pinmemberelchurichakravarthi2-Jul-14 18:12 
GeneralRe: Screenshots please! Pinmemberelchurichakravarthi2-Jul-14 18:30 
QuestionRe: Screenshots please! PinmemberRavimal Bandara5-Jul-14 7:00 
AnswerRe: Screenshots please! Pinprofessionalelchurichakravarthi5-Jul-14 18:39 
AnswerRe: Screenshots please! PinmemberRavimal Bandara5-Jul-14 22:34 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 2 Jul 2014
Article Copyright 2014 by Chakravarthi Elchuri
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid