Grouping Rows in a DataGrid






1.17/5 (16 votes)
Nov 20, 2004

95111

1736
Grouping Rows in a DataGrid using C# and ASP.NET.
Introduction
This is built off the same idea that Serge Lobko-Lobanovsky had in his article on here at http://www.codeproject.com/aspnet/GridGroupFormat.asp.
had trouble with the code he had posted and had to get it done for a project. Just call the method DataGridGroupBy(DataGrid dgYouWantGrouped, int ColumnToGroup)
of the DataGridGroupByRows
class in your WebForm and it will group all rows you want grouped together.
Here is the code for a class i wrote in the sample project attached:
using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace localhost
{
/// <SUMMARY>
/// Summary description for DataGridGrouper.
/// </SUMMARY>
public class DataGridGrouper
{
public DataGridGrouper()
{
//
// TODO: Add constructor logic here
//
}
public void GroupColumn(DataGrid dgMonitor, int ColumnIndex)
{
int ItemIndex= 0;
foreach(DataGridItem dgItem in dgMonitor.Items)
{
if(dgItem.ItemIndex > 0)
{ //if current cells text is the same as the cell above it
//make it invisible and increase the row span by 1 of the
//last visible cell in that column.
if(dgItem.Cells[ColumnIndex].Text ==
dgMonitor.Items[dgItem.ItemIndex-1].Cells[ColumnIndex].Text)
{
dgItem.Cells[ColumnIndex].Visible = false;
dgMonitor.Items[ItemIndex].Cells[ColumnIndex].RowSpan =
dgMonitor.Items[ItemIndex].Cells[ColumnIndex].RowSpan + 1;
}
else if(dgMonitor.Items[
dgItem.ItemIndex-1].Cells[ColumnIndex].Visible == true)
{
ItemIndex = dgItem.ItemIndex;
}
else
{
dgMonitor.Items[ItemIndex].Cells[ColumnIndex].RowSpan =
dgMonitor.Items[ItemIndex].Cells[ColumnIndex].RowSpan + 1;
ItemIndex = dgItem.ItemIndex;
}
}
}
//remove the extra row - might be good to know why i have to add an
//extra row.
dgMonitor.Items[dgMonitor.Items.Count-1].Visible = false;
}
}
}