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

Group GridView Data

By , 6 Oct 2010
 

Introduction

GridView is one of the most popular controls to display data in a tabular form. 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 easily. 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.

Below is a screenshot of grouped data in a GridView:

groupdemo3.jpg

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.

Below is the sample HTML code snippet 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>

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

License

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

About the Author

Anurag Gandhi
Software Developer (Senior) Sapient Consulting Pvt. Limited.
India India
Member
Anurag Gandhi is working on software design/development since last many years and he loves programming very much.
He is extensively Involved in Asp.Net web application development. The Language of his choice are C#.Net, Asp.Net, Asp, C, C++, etc. He works with MS Sql Server database as well.
He is active in programming communities and loves to share the knowledge with other developers whenever he gets the opportunity.
He is a passionate chess player as well.
 
He can be contacted at: soft.gandhi@gmail.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberAvik Ghosh2225 Feb '13 - 21:11 
useful code...thanks...
QuestionTwo Grid on same Pagemembernishat8 Oct '12 - 21:44 
This Customization is not working when we are using two gridview on same Page.
In this   case it will work for first Gridview but 2nd one it will not show groups.
 
Any solution?
 
Nishat
AnswerRe: Two Grid on same PagememberAnurag Gandhi9 Oct '12 - 8:42 
Thanks for your comment Nishat.
I will have a look into it in my free time and will let you know the possible solution.
Anurag Gandhi.
http://www.gandhisoft.com
Life is a computer program and every one is the programmer of his own life.
My latest article: Group GridView Data

QuestionPaging Doesn't workmemberAdam@DDI29 Aug '12 - 21:35 
Hi,
 
Nice control, appreciate your time and effort. I have been tweaking the control for my use and have run in to an issue with regards to implementing paging on the grid. Basically it doesn't seem to work.
 
In my scenario I am using a DataView that is querying an datasource and then binding that to the grid, displays the first page fine, however after you move to a different page (ensuring that you add the PageIndexChanging event handler to update the page and rebind) the data is not displayed (if I move to the second page I get one row, after that any other page shows no rows).
 
Are you able to assist with this please?
AnswerRe: Paging Doesn't workmemberAnurag Gandhi5 Sep '12 - 5:38 
Hi Adam,
The current version of the Control doesn't support paging.
I will update my control to support paging also.
 
Thanks for the good feedback.
Anurag Gandhi.
http://www.gandhisoft.com
Life is a computer program and every one is the programmer of his own life.
My latest article: Group GridView Data

GeneralRe: Paging Doesn't workmemberMember 968470113 Dec '12 - 23:42 
Is GroupGriedView with paging availbale now?
Questioncan't group custom datasource from list dinamics object [modified]memberionelDobrojan20 Aug '12 - 3:35 
Hi, i have a array of string, and from it i create datatable but cant group grid by column, my code:
DataTable getOtherDataTable()
{
DataTable table = new DataTable();
 
//Create 7 columns for this DataTable
DataColumn col1 = new DataColumn("Year");
DataColumn col2 = new DataColumn("Branch");
DataColumn col3 = new DataColumn("Gender");
DataColumn col4 = new DataColumn("College");
DataColumn col5 = new DataColumn("Name");
DataColumn col6 = new DataColumn("Marks");
//DataColumn col7 = new DataColumn("Remarks");
//Define DataType of the Columns
//col1.DataType = System.Type.GetType("System.Int");
//col2.DataType = System.Type.GetType("System.String");
//col3.DataType = System.Type.GetType("System.Boolean");
//col4.DataType = System.Type.GetType("System.String");
//col5.DataType = System.Type.GetType("System.Double");
//col6.DataType = System.Type.GetType("System.String");
//col7.DataType = System.Type.GetType("System.String");
//Add All These Columns into DataTable table
table.Columns.Add(col1);
table.Columns.Add(col2);
table.Columns.Add(col3);
table.Columns.Add(col4);
table.Columns.Add(col5);
table.Columns.Add(col6);
//table.Columns.Add(col7);
//Create a Row in the DataTable table
for (int i = 0; i < 10; i++)
{
string[] st = new string[6] { "year", "branch", "gender", "college", "nume", (20 * i).ToString() };
DataRow row = table.NewRow();
//Fill All Columns with Data
row[col1] = "year";
row[col2] = "branch";
row[col3] = "gender";
row[col4] = "college";
row[col5] = "nume";
row[col6] = 20 * i; ;
//row[col7] = "Purchased on July 30,2008";
//Add the Row into DataTable

table.Rows.Add(st);
//table.Rows[i].ItemArray = st;
}
table.DefaultView.Sort = "branch DESC";
return table;
}
private void BindGridView()
{
grdRawData.DataSource = getOtherDataTable();
grdRawData.DataBind();
}
If you have a sugestion in my problem please help

modified 20 Aug '12 - 9:48.

AnswerRe: can't group custom datasource from list dinamics objectmemberAnurag Gandhi5 Sep '12 - 5:45 
Hi what is error you are getting?
 
Did you set AllowGrouping and GroupColumnName Tags in your aspx page?
 
<gsoft:GroupGridView AllowGrouping="true" GroupColumnName="Year" 
Anurag Gandhi.
http://www.gandhisoft.com
Life is a computer program and every one is the programmer of his own life.
My latest article: Group GridView Data

QuestionI can't using for dotnetnukememberquythi.8912 May '12 - 4:50 
Hi all!!!
how to use GroupGridViewCtrl.dll in DotNetNuke ???
QuestionMy Vote of 5memberRaviRanjankr29 Oct '11 - 11:01 
Nice stuff. its helped me to understand how to grouping. thanks for share it. Thumbs Up | :thumbsup:

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 6 Oct 2010
Article Copyright 2010 by Anurag Gandhi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid