Click here to Skip to main content
15,878,852 members
Articles / Web Development / ASP.NET

Group GridView Data

Rate me:
Please Sign up or sign in to vote.
4.85/5 (57 votes)
22 Aug 2014CPOL5 min read 232.9K   12K   135   67
A custom GridView control which provides you an additional facility to group the data in gridview along with the facility to customise the Group Header and Group Footer

Introduction

GridView is one of the most popular controls to display data in a tabular format. But for better analysis, it requires to show the data in some summarized form like Group, Pivot, Graphs, Charts, etc. This article presents a simplified way to group your data with the appropriate aggregate functions so that you can enhance your reports with great ease. The facility to customize the group header and footer in your own way becomes the essential part when you are grouping your data. The control shown in the article has taken care of this requirement as well. If you are looking for the grouping grid in ASP.NET MVC, please have a look at Grouping Gridview in ASP.NET MVC.

Below is a screenshot of grouped data in a GridView:

GroupGridView/screen1.png

GroupGridView Control

GroupGridView control is a custom control derived from GridView. The primary purpose for this control is to implement the grouping feature in the GridView. To accommodate the customized group header and footer, GroupContainer class is created which is derived from WebControl and INamingContainer. This class is provided with various aggregate functions that can be applied to each group in your GridView. The useful methods in GroupHeaderTemplate and GroupFooterTemplate are:

  1. Average(ColumnName): Returns the average of the data present in the group for the given column
  2. Count(ColumnName): Returns the total number of rows present in the group for the given column
  3. First(ColumnName): Returns the first element of the given column in the group
  4. Last(ColumnName): Returns the last element of the given column in the group
  5. Max(ColumnName): Returns the maximum value of the data present in the group for the given column
  6. Min(ColumnName): Returns the minimum value of the data present in the group for the given column
  7. Sum(ColumnName): Returns the sum of data present in the group for the given column
  8. GetValue(DataColumn, PropertyColumn, MatchingValue): Returns the value of the DataColumn whose PropertyColumn is equal to the MatchingValue

How It Works

The logic behind grouping the data in GridView can be divided into three parts:

  1. Instantiate the HeaderTemplate Template: To do this, custom control has been created with two exposed properties: GroupHeaderTemplate and GroupFooterTemplate. This template needs to be instantiated for each group present in your DataSource. This has been done by overriding the PrepareControlHierarchy() method of GridView.
  2. Recognize Group and Render Group Header at proper place: To recognize the group, I have overridden OnRowCreated() method of the GridView and added "group" attribute and its value to each row of the table. To align Header and Footer at proper place, JQuery has been used.
  3. Providing Hide/Show functionality to the group: The hide/show functionality to each group has been provided using JQuery. Please have a look at the RenderClientSideGroup() method to understand the JQuery code used to FadeIn and FadeOut the Group(s). You don't need to learn JQuery to use this control.

Using the Code

Using the code is simple. The control is provided with two additional Template Containers: GroupHeaderTemplate and GroupFooterTemplate. Both of these Template containers provide you the facility to write your own custom HTML code and use Aggregation logic to format your Header and Footer of the each group of GridView.

GroupGridView/screen2.png

Below is the sample aspx markup which you can write to make this control work (don't forget to include JQuery file in your code):

HTML
//Copy the GroupGridViewCtrl.dll to your bin directory. Add reference.//
<%@ Register Assembly="GroupGridViewCtrl" 
    Namespace="GroupGridViewCtrl" TagPrefix="gsoft" %>
...
<script type="text/javascript" language="javascript" 
    src="js/jquery-1.4.2.min.js"></script>
...
<gsoft:GroupGridView AllowGrouping="true" GroupColumnName="Year" 
...
<GroupHeaderTemplate>
    <div style="background-color:#ccddff;">
        <table style="width:100%;">
            <tr>
                <td style="width:50%; font-weight:bold;">
        <%# Container.GroupColumnName + ": " + 
            Container.GroupColumnData.ToString() %> </td>
                <td style="width:50%;">Total Students: 
            <%# Container.Count("Name") %></td>
            </tr>
            <tr>
                <td>Average Marks: <%# Math.Round((decimal)
            Container.Average("Marks"), 2) %></td>
                <td>Highest: <%# Container.Max("Marks") %></td>
            </tr>
            <tr>
                <td colspan="2">Topper: <%# Container.GetValue
        ("Name", "Marks", Container.Max("Marks").ToString())%></td>
            </tr>
        </table>
    </div>
</GroupHeaderTemplate>  

To make this control work, don't forget to set AllowGrouping property to true. Moreover, GroupColumnName property must be set to the correct value.

More Options

Based on various feedback/emails of the readers, I have included some more options in this version of GroupGridView Control. Some of them are as follows:

  • DefaultState: This control now has a property called DefaultState which determines whether to keep the grouped data collapsed or expanded by default.
  • Multiple Grids in a Page: The current version of GroupGridView control now allows you to have multiple GroupGridView controls in a page working simultaneously.
  • EmptyGroupFooter: When the group footer is not needed, you may now simply omit the GroupFooterTemplate tag.
  • Paging: You may implement your normal paging behaviour of the GridView in this control, but, you need to understand that this control will group the data of the current page only. If you are implementing paging, you must watch and understand the behavior of aggregate functions used in Group Headers and Footers.
  • Grouping in Update Panel, etc.: In the previous version, one of the issues reported that Grouping behavior eliminates when update panel updated. In such scenarios, a JavaScript function "ApplyGrouping_ + ClientId of gridview" can be called when UpdatePanel got updated and it will apply the grouping behavior again. You may also use the above mentioned function to apply the grouping when grouping by default is not working due to some JavaScript error or something else.
  • ClientSide Options: Based on request from the readers, I have provided the option to expand/collapse the various parts of gridview from JavaScript. The attached sample provides you the sample code for expanding/collapsing Headers, Footers and data using JavaScript. You may explore more about it yourself.

Points of Interest

Along with grouping the data in GridView, the sample will also provide the following things to the beginners:

  1. How to create a custom control
  2. How to create and use Template/Container Control
  3. How to read data from Excel Sheet
  4. How to use Linq to filter DataTable data

History

  • 5th October, 2010: First version release
  • 9th June, 2013: Version 1.1
  • 12th June, 2013: Version 1.2: Added client side options

License

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


Written By
Architect
India India
Anurag Gandhi is a Freelance Developer and Consultant, Architect, Blogger, Speaker, and Ex Microsoft Employee. He is passionate about programming.
He is extensively involved in Asp.Net Core, MVC/Web API, Node/Express, Microsoft Azure/Cloud, web application hosting/architecture, Angular, AngularJs, design, and development. His languages of choice are C#, Node/Express, JavaScript, Asp .NET MVC, Asp, C, C++. He is familiar with many other programming languages as well. He mostly works with MS SQL Server as the preferred database and has worked with Redis, MySQL, Oracle, MS Access, etc. also.
He is active in programming communities and loves to share the knowledge with others whenever he gets the time for it.
He is also a passionate chess player.
Linked in Profile: https://in.linkedin.com/in/anuraggandhi
He can be contacted at soft.gandhi@gmail.com

Comments and Discussions

 
QuestionApplyGrouping Pin
Toni Esteso11-Jun-20 22:33
Toni Esteso11-Jun-20 22:33 
QuestionPaging in Grouped Gridview Pin
AbdulMatin_M17-Mar-19 3:24
AbdulMatin_M17-Mar-19 3:24 
AnswerRe: Paging in Grouped Gridview Pin
Anurag Gandhi15-Apr-21 6:05
professionalAnurag Gandhi15-Apr-21 6:05 
SuggestionWPF Pin
RickZeeland24-Jun-15 21:56
mveRickZeeland24-Jun-15 21:56 
GeneralRe: WPF Pin
Anurag Gandhi27-Jun-15 19:51
professionalAnurag Gandhi27-Jun-15 19:51 
QuestionValue cannot be null. Parameter name: source Pin
sanj_roman14-Dec-14 20:36
sanj_roman14-Dec-14 20:36 
AnswerRe: Value cannot be null. Parameter name: source Pin
Anurag Gandhi14-Dec-14 22:14
professionalAnurag Gandhi14-Dec-14 22:14 
GeneralRe: Value cannot be null. Parameter name: source Pin
sanj_roman15-Dec-14 0:40
sanj_roman15-Dec-14 0:40 
GeneralRe: Value cannot be null. Parameter name: source Pin
Anurag Gandhi15-Dec-14 0:50
professionalAnurag Gandhi15-Dec-14 0:50 
GeneralRe: Value cannot be null. Parameter name: source Pin
sanj_roman15-Dec-14 1:10
sanj_roman15-Dec-14 1:10 
QuestionCouldn't get it to work in SP2010 webpart Pin
Mike Nguyen5-Nov-14 5:06
Mike Nguyen5-Nov-14 5:06 
AnswerRe: Couldn't get it to work in SP2010 webpart Pin
Anurag Gandhi5-Nov-14 20:05
professionalAnurag Gandhi5-Nov-14 20:05 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun21-May-14 20:19
Humayun Kabir Mamun21-May-14 20:19 
GeneralRe: My vote of 5 Pin
Anurag Gandhi25-Aug-14 4:46
professionalAnurag Gandhi25-Aug-14 4:46 
QuestionError: '$' is undefined Error Pin
Member 1034500723-Apr-14 11:42
Member 1034500723-Apr-14 11:42 
AnswerRe: Error: '$' is undefined Error Pin
Anurag Gandhi24-Apr-14 9:02
professionalAnurag Gandhi24-Apr-14 9:02 
GeneralRe: Error: '$' is undefined Error Pin
Member 1034500724-Apr-14 14:29
Member 1034500724-Apr-14 14:29 
Questionasp:ButtonField creates runtime error in PrepareControlHierarchy() Pin
Member 305191918-Aug-13 6:46
Member 305191918-Aug-13 6:46 
AnswerRe: asp:ButtonField creates runtime error in PrepareControlHierarchy() Pin
Anurag Gandhi18-Aug-13 23:10
professionalAnurag Gandhi18-Aug-13 23:10 
QuestionJavascript to Expand /Collaps a single group Pin
Member 305191918-Aug-13 3:55
Member 305191918-Aug-13 3:55 
AnswerRe: Javascript to Expand /Collaps a single group Pin
Anurag Gandhi18-Aug-13 5:02
professionalAnurag Gandhi18-Aug-13 5:02 
QuestionSet the Width of the GroupHeader Pin
Member 1020444215-Aug-13 3:56
professionalMember 1020444215-Aug-13 3:56 
AnswerRe: Set the Width of the GroupHeader Pin
Anurag Gandhi17-Aug-13 4:42
professionalAnurag Gandhi17-Aug-13 4:42 
GeneralRe: Set the Width of the GroupHeader Pin
Member 1020444218-Aug-13 22:20
professionalMember 1020444218-Aug-13 22:20 
Questionsuperb article Pin
shubham14720-Jun-13 9:07
shubham14720-Jun-13 9:07 

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.