Sunday, June 24, 2007

GridView: The Very Simple Grouping

While there are many many third party grid components on the market, it is often necessary to support and enhance existing applications and they often employ GridView to display and edit data.  One of the features that standard GridView lacks is a very simple grouping. 

I know several ways to display grouped data in a grid.  The following is quite flexible when you need to display data with multiple nested groupings. 

 GridViewGrouping

Moreover, this grouping style is very easy to accomplish by hooking two GridView events:  RowDataBound and DataBound.

The desired view is built by setting RowSpan property on the first row in the group and hiding first cell in each subsequent row in the group.

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
DataRowView currentDataRowView = (DataRowView)e.Row.DataItem;
if (currentDataRowView != null) {
DataRow currentDataRow = currentDataRowView.Row;
if (m_firstGroupDataRow != null) {
object lastValue = m_firstGroupDataRow["ProductSubcategoryID"];
object currentValue = currentDataRow["ProductSubcategoryID"];
if (currentValue.Equals(lastValue)) {
m_rowSpan++;
e.Row.Cells[0].Visible = false;
return;
}
if (m_rowSpan > 1) {
m_firstGroupGridRow.Cells[0].RowSpan = m_rowSpan;
}
}
m_firstGroupGridRow = e.Row;
m_firstGroupDataRow = currentDataRow;
m_rowSpan = 1;
}
}

protected void GridView1_DataBound(object sender, EventArgs e) {
if (m_rowSpan > 1) {
m_firstGroupGridRow.Cells[0].RowSpan = m_rowSpan;
}
}

The code snipped is only to illustrate the approach.  It is usually better to move this code into the standalone class.  Instances of this class can be configured to extend the GridView control behavior.


Sample implementation of GridViewGroup class based on these code snippets are available in the attachment: GridViewGroup.zip.


This code snippet demonstrates one of three steps necessary to get GridView display data with grouping:

    protected void GridView1_DataBinding(object sender, EventArgs e) {
GridViewGroup first = new GridViewGroup(GridView1, null, "ProductSubcategoryID");
GridViewGroup second = new GridViewGroup(GridView1, first, "Color");
}

 The other steps are:



  1. Order your data source by grouping columns in the first place

  2. Add GridView1_DataBinding handler to your GridView DataBinding event

The result is:


GridView2

2 comments:

Anonymous said...

Implement the same thing with column span, and possibly a combination of both.

Thanks

dotNetSoldier said...

Now the data grouping in gridview is made simple than ever before...

Try this free grouping gridview control with zero coding effort !

http://znetcontrols.blogspot.com/2008/08/extended-gridview-for-aspnet-20-with.html

HTH