Click here to Skip to main content
13,152,321 members (39,594 online)
Click here to Skip to main content
Add your own
alternative version

Stats

84.9K views
8.9K downloads
99 bookmarked
Posted 20 Jan 2015

Nested DataGridView in windows forms c#

, 20 Jan 2015
Rate this:
Please Sign up or sign in to vote.
Nested or Master Detail or Hierarchical DataGridView for winforms

Introduction

In my previous article I have explained about how to create a DatagGridView helper class using c# click this link to view my previous article.

I have extended the DatagGridView Helper class to create a Nested DatagGridView. Few days before one of codeproject member asked a question on how to create a Nested or Master Detail or Hierarchical DataGridView for winforms. I started searching in Google but badly I didn’t get any result for nested DataGridView .I started working on creating a Nested DataGridView sample program which should be useful to all. As a result I have created a Nested DataGridView and you can find the source code from this article. My aim is to create a simple and easy program for users. User can download the code and can customize depend on their requirement.

Why we need Nested or Hierarchical DataGridView

In real time projects like Order Management, Production management and etc. we need to display the data in the hierarchical result.

For example let’s take Order Management project for a restaurant. Let’s consider four peoples going to a restaurant to have their lunch. The waiter from the restaurant will give a menu card to select the item to place an order. Now in a Table total 4 peoples are sitting. In a restaurant management usually for all tables there will be a unique Table Id or name. All 4 peoples will select their item need from menu card and place the order to serve their food. In restaurant management for each order we will create a unique Id in an Order Master table and all the item details related to the order in Order Detail table. Let’s see an example structure of the order.

Why we need Master and Detail Table? To avoid the duplicate data we can use the master Detail table relation to store our data. For example for every order there will be one waiter and one Table so if we didn’t use the Master Detail table relation the output will be like this below.

Here we can see that Order No, Table ID, Waiter Name and order Date has been repeated. To avoid this duplicate data we will create a Master and Detail relation tables .See the below table for Master and Details.

Order Master Table

Here we can see the duplicate data has been stored in separate table as a Order Master Table.

Order Detail Table

Here we can see all the item details of order in separate table. But in the detail table we have used the Order NO for a relation to the Master table. Using the relation we can combine both the table and produce the out output.

Normal grid result:

The result can be shown without using the Hierarchal grid output .But we have to display the duplicate result as below.

We can also merge the same data and show the result like this below table. But the output is not much good and not easy to view and understand.

Let’s see now the hierarchical output of the same result.

Now this final result looks much better then all. It will be easy to view the master and detail of all records.

Here is my sample output of hierarchical Datagridview.

Same like Order Management in Restaurant projects we will have Bill Master and Detail, Account Master and Detail. Item Master and Detail, Inventory Master and Detail. In production projects we will have Production Order Master and Oder Detail, Finished Good Receipt Master and Detail, Finished Goods Issue Master and Detail and etc. Same like this in our all real time projects we will use the Master and detail relation to display our data.

Using the code

As I told you in this article that I have used and extended my DataGridView helper class to create a Nested DataGridView. You can view my DataGridView helper class details from my article.

In my DGVhelper class I have added the below functionality to create the nested grid.

  • ImageCoulmn
  • DGVMasterGridClickEvents
  • DGVDetailGridClickEvents

User can use all events like CellClick, CellContentClick and etc for both Master and Detail grid.

I have created two separate list class to populate the master and detail result. In form load called the method to add the details to each list class.

I have created both Master and Detail Datagridview programmatically (Dynamically) Using my ShanuDGVHelper Class.

Master Grid Setting: In Form load I have called this method to create a master DataGridView at runtime.

In my code I add the comments before each line to explain its use.

// to generate Master Datagridview with your coding
     public void MasterGrid_Initialize()
     {

         //First generate the grid Layout Design
         Helper.ShanuDGVHelper.Layouts(Master_shanuDGV, Color.LightSteelBlue, Color.AliceBlue, Color.WhiteSmoke, false, Color.SteelBlue, false, false, false);

         //Set Height,width and add panel to your selected control
         Helper.ShanuDGVHelper.Generategrid(Master_shanuDGV, pnlShanuGrid, 1000, 600, 10, 10);


         // Color Image Column creation
         Helper.ShanuDGVHelper.Templatecolumn(Master_shanuDGV, ShanuControlTypes.ImageColumn, "img", "", "", true, 26, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null, "", "", Color.Black);

         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Master_shanuDGV, ShanuControlTypes.BoundColumn, "Order_No", "Order NO", "Order NO", true, 90, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);

         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Master_shanuDGV, ShanuControlTypes.BoundColumn, "Table_ID", "Table ID", "Table ID", true, 80, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Master_shanuDGV, ShanuControlTypes.BoundColumn, "Description", "Description", "Description", true, 320, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Master_shanuDGV, ShanuControlTypes.BoundColumn, "Order_DATE", "Order DATE", "Order DATE", true, 140, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Master_shanuDGV, ShanuControlTypes.BoundColumn, "Waiter_ID", "Waiter_ID", "Waiter_ID", true, 120, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         //Convert the List to DataTable
         DataTable detailTableList = ListtoDataTable(DataClass.OrderDetailBindClass.objDetailDGVBind);

         // Image Colum Click Event - In  this method we create an event for cell click and we will display the Detail grid with result.

         objshanudgvHelper.DGVMasterGridClickEvents(Master_shanuDGV, Detail_shanuDGV, Master_shanuDGV.Columns["img"].Index, ShanuEventTypes.cellContentClick, ShanuControlTypes.ImageColumn, detailTableList, "Order_No");

         // Bind data to DGV.
         Master_shanuDGV.DataSource = DataClass.OrderMasterBindClass.objMasterDGVBind;
     }

Cell Click Event: I have called this above method to create a Cell click event for master DataGridView.

// Image Colum Click Event - In  this method we create an event for cell click and we will display the Detail grid with result.
           objshanudgvHelper.DGVMasterGridClickEvents(Master_shanuDGV, Detail_shanuDGV, Master_shanuDGV.Columns["img"].Index, ShanuEventTypes.cellContentClick, ShanuControlTypes.ImageColumn, detailTableList, "Order_No");

This event will be used for the master grid Image click event. In this Event i will get the Order No and filter the result from DataTabledetail .Display the final Dataview result to Detail DataGridView.

public void DGVMasterGridClickEvents(DataGridView ShanuMasterDGV, DataGridView ShanuDetailDGV, int columnIndexs, ShanuEventTypes eventtype, ShanuControlTypes types,DataTable DetailTable,String FilterColumn)
      {
          MasterDGVs = ShanuMasterDGV;
          DetailDGVs = ShanuDetailDGV;
          gridColumnIndex = columnIndexs;
          DetailgridDT = DetailTable;
          FilterColumnName = FilterColumn;

          MasterDGVs.CellContentClick += new DataGridViewCellEventHandler(masterDGVs_CellContentClick_Event);


      }
      private void masterDGVs_CellContentClick_Event(object sender, DataGridViewCellEventArgs e)
      {

          DataGridViewImageColumn cols = (DataGridViewImageColumn)MasterDGVs.Columns[0];

         // cols.Image = Image.FromFile(ImageName);
          MasterDGVs.Rows[e.RowIndex].Cells[0].Value = Image.FromFile("expand.png");

           if (e.ColumnIndex == gridColumnIndex)
           {


               if (ImageName == "expand.png")
               {
                   DetailDGVs.Visible = true;
                   ImageName = "toggle.png";
                   // cols.Image = Image.FromFile(ImageName);
                   MasterDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Image.FromFile(ImageName);


                   String Filterexpression = MasterDGVs.Rows[e.RowIndex].Cells[FilterColumnName].Value.ToString();

                   MasterDGVs.Controls.Add(DetailDGVs);

                   Rectangle dgvRectangle = MasterDGVs.GetCellDisplayRectangle(1, e.RowIndex, true);
                   DetailDGVs.Size = new Size(MasterDGVs.Width - 200, 200);
                   DetailDGVs.Location = new Point(dgvRectangle.X, dgvRectangle.Y + 20);


                   DataView detailView = new DataView(DetailgridDT);
                   detailView.RowFilter = FilterColumnName + " = '" + Filterexpression + "'";
                   if (detailView.Count <= 0)
                   {
                       MessageBox.Show("No Details Found");
                   }
                   DetailDGVs.DataSource = detailView;


               }
               else
               {
                   ImageName = "expand.png";
                   //  cols.Image = Image.FromFile(ImageName);
                   MasterDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = Image.FromFile(ImageName);
                   DetailDGVs.Visible = false;
               }
           }
           else
           {
               DetailDGVs.Visible = false;

           }
      }

In cell click event if the image column is clicked. I will change the image to Expand and Collapse depends on the selected image name.

If the image is selected to Expand then I will make visible of the detail DataGridView.

In cell click event I will get for the current selected Order No. This order No will be used in “DataView” to filter only the selected order result. The Final result will be bind to the Detail DataGridView.

Detail Grid Setting: In Form load I have called this method to create a Detail DataGridView at runtime.

In my code I add the comments before each line to explain its use.

// to generate Detail Datagridview with your coding
     public void DetailGrid_Initialize()
     {

         //First generate the grid Layout Design
         Helper.ShanuDGVHelper.Layouts(Detail_shanuDGV, Color.Peru, Color.Wheat, Color.Tan, false, Color.Sienna, false, false, false);

         //Set Height,width and add panel to your selected control
        Helper.ShanuDGVHelper.Generategrid(Detail_shanuDGV, pnlShanuGrid, 800, 200, 10, 10);

         // Color Dialog Column creation
         Helper.ShanuDGVHelper.Templatecolumn(Detail_shanuDGV, ShanuControlTypes.BoundColumn, "Order_Detail_No", "Detail No", "Order Detail No", true, 90, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleCenter, DataGridViewContentAlignment.MiddleRight, Color.Transparent, null, "", "", Color.Black);

         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Detail_shanuDGV, ShanuControlTypes.BoundColumn, "Order_No", "Order NO", "Order NO", true, 80, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);

         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Detail_shanuDGV, ShanuControlTypes.BoundColumn, "Item_Name", "Item_Name", "Item_Name", true,160, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Detail_shanuDGV, ShanuControlTypes.BoundColumn, "Notes", "Notes", "Notes", true, 260, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleLeft, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Detail_shanuDGV, ShanuControlTypes.BoundColumn, "Price", "Price", "Price", true, 70, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);


         // BoundColumn creation
         Helper.ShanuDGVHelper.Templatecolumn(Detail_shanuDGV, ShanuControlTypes.BoundColumn, "QTY", "QTY", "QTY", true, 40, DataGridViewTriState.True, DataGridViewContentAlignment.MiddleRight, DataGridViewContentAlignment.MiddleCenter, Color.Transparent, null, "", "", Color.Black);
         objshanudgvHelper.DGVDetailGridClickEvents(Detail_shanuDGV);

     }

Detail Grid Cell Click Event: I have called this above method to create a Cell click event for Detail DataGridView.

objshanudgvHelper.DGVDetailGridClickEvents(Detail_shanuDGV);

This event will be used for the Detail grid Cell Click Event. In cell click of Detail grid i will get the each cell text and display in the Messagebox.

  public void DGVDetailGridClickEvents(DataGridView ShanuDetailDGV)
    {

        DetailDGVs = ShanuDetailDGV;

        DetailDGVs.CellContentClick += new DataGridViewCellEventHandler(detailDGVs_CellContentClick_Event);


    }
      private void detailDGVs_CellContentClick_Event(object sender, DataGridViewCellEventArgs e)
      {
          MessageBox.Show("Detail grid Clicked : You clicked on " + DetailDGVs.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);
      }

}

Points of Interest

This program explains the basic functions to create single level Hierarchical DataGridView. This same functionality can be used to create multi level Hierarchical DataGridView.

History

Version 1.0 - > 2014-12-02.

License

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

Share

About the Author

syed shanu
Team Leader
India India

Microsoft MVP 2016


My Interview on Microsoft TechNet Wiki Ninja Link




His Blog


Syed Shanu is basically from Madurai, Tamil Nadu, India.He was been working in South Korea for past 8 years. He started programming with Basic Language and C language from his high school at 1999.In 2005 he completed his Master of Computer Application. He started his working Career from Dec 2004 with ASP.

He has 10+ years of Experience in Microsoft Technologies.

His work experience with Language and Technology start’s from ASP and SQL Server, Then VB.NET and C# for PDA Application, Touch Screen Application Development, Desktop Application, ASP.NET Web Application Development, MVC and WPF.

He loves to work with Microsoft technology as he started to work on .Net Frame Work version from 1.0 to 4.5.

He had worked with HMI (Human Machine Interface) programs like PLC, Nutrunner Tools, and Sensor programs, RFID programs, Barcode programs and etc.

He usually uses his free time to spend with his Family and go outing. He loves photography and Hiking.

ASP.NET Article of the Day

1) Title : Draw ASP.NET Bar Chart Using HTML5 and jQuery Date : July 8, 2015
2) Title : ASP.NET Web Photo Editing Tool using HTML 5 Date : July 8, 2015
3) Title : MVC AngularJS and WCF Rest Service For Mind Reader Quiz Date : May 18, 2015
4) Title : AngularJS Shopping Cart Using MVC and WCF Rest Service Date : April 10, 2015
5) Title : Insert select update delete in asp.net with Simple Log
6) Title : Project Scheduling Using ASP.Net GridView Date : December 26, 2014
7) Title : ASP.NET Web Painting Tool using HTML 5 Date : September 16, 2014

You may also be interested in...

Comments and Discussions

 
Questionadding Image Pin
Member 1167195016-Apr-17 22:04
memberMember 1167195016-Apr-17 22:04 
QuestionDuplicated Data Pin
juste_3al_faza21-Nov-16 21:56
memberjuste_3al_faza21-Nov-16 21:56 
GeneralMy vote of 4 Pin
Muhammad Shahid Farooq9-Aug-16 19:32
professionalMuhammad Shahid Farooq9-Aug-16 19:32 
QuestionNot a DataGridView nesting! Pin
dimitrios georgiadis27-Jun-16 1:40
memberdimitrios georgiadis27-Jun-16 1:40 
QuestionLoading the data from DB... Pin
Member 1228965416-Mar-16 1:00
memberMember 1228965416-Mar-16 1:00 
QuestionLoad DGV using SQL select or stored procedure Pin
Member 1198959912-Oct-15 3:47
memberMember 1198959912-Oct-15 3:47 
AnswerRe: Load DGV using SQL select or stored procedure Pin
syed shanu16-Mar-16 3:08
mvpsyed shanu16-Mar-16 3:08 
GeneralRe: Load DGV using SQL select or stored procedure Pin
Eric Piper25-Jul-17 10:38
memberEric Piper25-Jul-17 10:38 
GeneralImage column adding Pin
me.pankajpathak20-Jul-15 0:41
memberme.pankajpathak20-Jul-15 0:41 
GeneralRe: Image column adding Pin
syed shanu20-Jul-15 13:31
mvpsyed shanu20-Jul-15 13:31 
Questiongood example Pin
Đặng Phi Sơn21-Dec-14 16:48
memberĐặng Phi Sơn21-Dec-14 16:48 
AnswerRe: good example Pin
syed shanu21-Dec-14 16:49
professionalsyed shanu21-Dec-14 16:49 
QuestionMerge same data Pin
Member 1045473019-Dec-14 22:15
memberMember 1045473019-Dec-14 22:15 
AnswerRe: Merge same data Pin
syed shanu19-Dec-14 22:27
professionalsyed shanu19-Dec-14 22:27 
GeneralRe: Merge same data Pin
Frintani19-Dec-14 22:33
memberFrintani19-Dec-14 22:33 
GeneralRe: Merge same data Pin
syed shanu19-Dec-14 22:50
professionalsyed shanu19-Dec-14 22:50 
GeneralRe: Merge same data Pin
Frintani20-Dec-14 0:08
memberFrintani20-Dec-14 0:08 
GeneralRe: Merge same data Pin
syed shanu20-Dec-14 0:17
professionalsyed shanu20-Dec-14 0:17 
GeneralRe: Merge same data Pin
Frintani21-Dec-14 1:35
memberFrintani21-Dec-14 1:35 
General5 Star, finally, i see this happen. Pin
Cheung Tat Ming8-Dec-14 16:38
memberCheung Tat Ming8-Dec-14 16:38 
GeneralRe: 5 Star, finally, i see this happen. Pin
syed shanu8-Dec-14 16:51
professionalsyed shanu8-Dec-14 16:51 
QuestionDefect Pin
Youzelin7-Dec-14 21:25
memberYouzelin7-Dec-14 21:25 
AnswerRe: Defect Pin
syed shanu7-Dec-14 21:30
professionalsyed shanu7-Dec-14 21:30 
Question5 stars!!! good post Pin
GREG_DORIANcod4-Dec-14 3:47
memberGREG_DORIANcod4-Dec-14 3:47 
AnswerRe: 5 stars!!! good post Pin
syed shanu4-Dec-14 13:21
professionalsyed shanu4-Dec-14 13:21 
QuestionMessage Closed Pin
2-Dec-14 22:30
memberThornik2-Dec-14 22:30 
AnswerRe: misuse of "nested" Pin
syed shanu3-Dec-14 14:17
professionalsyed shanu3-Dec-14 14:17 
GeneralRe: misuse of "nested" Pin
Thornik4-Dec-14 0:10
memberThornik4-Dec-14 0:10 
GeneralRe: misuse of "nested" Pin
syed shanu4-Dec-14 1:11
professionalsyed shanu4-Dec-14 1:11 
GeneralRe: misuse of "nested" Pin
Thornik4-Dec-14 1:20
memberThornik4-Dec-14 1:20 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun2-Dec-14 16:54
memberHumayun Kabir Mamun2-Dec-14 16:54 
GeneralMy vote of 5 Pin
Emre Ataseven2-Dec-14 7:52
professionalEmre Ataseven2-Dec-14 7:52 
GeneralRe: My vote of 5 Pin
syed shanu2-Dec-14 12:54
professionalsyed shanu2-Dec-14 12:54 
QuestionOne suggestion Pin
Tridip Bhattacharjee1-Dec-14 20:10
memberTridip Bhattacharjee1-Dec-14 20:10 
AnswerRe: One suggestion Pin
syed shanu1-Dec-14 20:12
professionalsyed shanu1-Dec-14 20:12 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.170924.2 | Last Updated 20 Jan 2015
Article Copyright 2015 by syed shanu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid