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

Group GridView Data

, 22 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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 articles presents a simplified way to group your data with the appropriate aggregate functions so that you can enhance your reports with a great ease. 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 over http://www.codeproject.com/Articles/761687/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 over 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):

 

//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 previous version, one of the issue 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

  • First version release: October 05, 2010
  • Version 1.1: June 09, 2013
  • Version 1.2: June 12, 2013: Added client side options.

License

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

Share

About the Author

Anurag Gandhi
Technical Lead
India India
Anurag Gandhi currently works in web application design/development and has done so for many years now as he is passionate about programming.
He is extensively involved in Asp.Net and Asp.Net MVC web application architecture, AngularJs, design and development. His languages of choice are C#, Asp.Net, MVC, Asp, C, C++. But he is familiar with many other coding languages. He works with MS Sql Server as the database architecture of choice.
He is active in programming communities and loves to share his knowledge with other developers whenever he gets the opportunity.
He is also a passionate chess player.
 
He can be contacted at: soft.gandhi@gmail.com
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionValue cannot be null. Parameter name: source Pinmembersanj_roman14-Dec-14 21:36 
AnswerRe: Value cannot be null. Parameter name: source PinprofessionalAnurag Gandhi14-Dec-14 23:14 
GeneralRe: Value cannot be null. Parameter name: source Pinmembersanj_roman15-Dec-14 1:40 
GeneralRe: Value cannot be null. Parameter name: source PinprofessionalAnurag Gandhi15-Dec-14 1:50 
GeneralRe: Value cannot be null. Parameter name: source Pinmembersanj_roman15-Dec-14 2:10 
QuestionCouldn't get it to work in SP2010 webpart PinmemberMike Nguyen5-Nov-14 6:06 
AnswerRe: Couldn't get it to work in SP2010 webpart PinprofessionalAnurag Gandhi5-Nov-14 21:05 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun21-May-14 21:19 
GeneralRe: My vote of 5 PinprofessionalAnurag Gandhi25-Aug-14 5:46 
QuestionError: '$' is undefined Error PinmemberMember 1034500723-Apr-14 12:42 
AnswerRe: Error: '$' is undefined Error PinprofessionalAnurag Gandhi24-Apr-14 10:02 
GeneralRe: Error: '$' is undefined Error PinmemberMember 1034500724-Apr-14 15:29 
Questionasp:ButtonField creates runtime error in PrepareControlHierarchy() PinmemberMember 305191918-Aug-13 7:46 
AnswerRe: asp:ButtonField creates runtime error in PrepareControlHierarchy() PinmemberAnurag Gandhi19-Aug-13 0:10 
QuestionJavascript to Expand /Collaps a single group PinmemberMember 305191918-Aug-13 4:55 
AnswerRe: Javascript to Expand /Collaps a single group PinmemberAnurag Gandhi18-Aug-13 6:02 
QuestionSet the Width of the GroupHeader PinmemberMember 1020444215-Aug-13 4:56 
AnswerRe: Set the Width of the GroupHeader PinmemberAnurag Gandhi17-Aug-13 5:42 
GeneralRe: Set the Width of the GroupHeader PinprofessionalMember 1020444218-Aug-13 23:20 
Questionsuperb article Pingroupshubham14720-Jun-13 10:07 
AnswerRe: superb article PinmemberAnurag Gandhi20-Jun-13 18:11 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun13-Jun-13 4:10 
GeneralRe: My vote of 5 PinmemberAnurag Gandhi14-Jun-13 22:30 
GeneralMy vote of 5 PinprofessionalMohamedKamalPharm12-Jun-13 15:48 
GeneralRe: My vote of 5 PinmemberAnurag Gandhi14-Jun-13 22:30 
QuestionCollapsible Groups possibel? PinmemberMember 305191910-Jun-13 22:56 
AnswerRe: Collapsible Groups possibel? PinmemberAnurag Gandhi11-Jun-13 2:29 
AnswerRe: Collapsible Groups possibel? PinmemberAnurag Gandhi12-Jun-13 4:46 
GeneralRe: Collapsible Groups possibel? PinmemberMember 305191913-Jun-13 0:09 
GeneralMy vote of 5 PinprofessionalPrasad Khandekar9-Jun-13 9:55 
GeneralRe: My vote of 5 PinmemberAnurag Gandhi11-Jun-13 2:27 
GeneralMy vote of 5 PinmemberAvik Ghosh2225-Feb-13 22:11 
GeneralRe: My vote of 5 PinmemberAnurag Gandhi8-Jun-13 23:37 
QuestionTwo Grid on same Page Pinmembernishat8-Oct-12 22:44 
AnswerRe: Two Grid on same Page PinmemberAnurag Gandhi9-Oct-12 9:42 
AnswerRe: Two Grid on same Page PinmemberAnurag Gandhi8-Jun-13 23:37 
QuestionPaging Doesn't work PinmemberAdam@DDI29-Aug-12 22:35 
AnswerRe: Paging Doesn't work PinmemberAnurag Gandhi5-Sep-12 6:38 
GeneralRe: Paging Doesn't work PinmemberMember 968470114-Dec-12 0:42 
GeneralRe: Paging Doesn't work PinmemberAnurag Gandhi8-Jun-13 23:34 
Questioncan't group custom datasource from list dinamics object [modified] PinmemberionelDobrojan20-Aug-12 4:35 
AnswerRe: can't group custom datasource from list dinamics object PinmemberAnurag Gandhi5-Sep-12 6:45 
AnswerRe: can't group custom datasource from list dinamics object PinmemberMember 187781825-Jun-14 12:44 
QuestionI can't using for dotnetnuke Pinmemberquythi.8912-May-12 5:50 
QuestionMy Vote of 5 PinmemberRaviRanjankr29-Oct-11 12:01 
AnswerRe: My Vote of 5 PinmemberAnurag Gandhi30-Oct-11 0:23 
QuestionI Face Problem in issue Pinmemberwalaalolo18-Sep-11 1:05 
AnswerRe: I Face Problem in issue PinmemberAnurag Gandhi21-Sep-11 18:38 
AnswerRe: I Face Problem in issue PinmemberAnurag Gandhi8-Jun-13 23:38 
GeneralMy vote of 5 PinmemberSwaminathan2028-Jan-11 2:31 

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
Web01 | 2.8.141223.1 | Last Updated 22 Aug 2014
Article Copyright 2010 by Anurag Gandhi
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid