Click here to Skip to main content
6,292,811 members and growing! (10,163 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Separating Datagrid Items

By Marcie Jones

How to add a separator row to set off groups of similar data in an ASP.NET Datagrid
VB.NET 1.0, .NET 1.1, Win2K, WinXP, Win2003, ASP.NET, Visual Studio, Dev
Posted:9 Feb 2004
Views:138,763
Bookmarked:51 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
26 votes for this article.
Popularity: 5.86 Rating: 4.14 out of 5
2 votes, 7.7%
1
1 vote, 3.8%
2
1 vote, 3.8%
3
4 votes, 15.4%
4
18 votes, 69.2%
5
Separated Datagrid

Introduction

For those that don't know me, I run a website about the ASP.NET Datagrid control, http://www.datagridgirl.com/.  Inevitably, my first article here at CodeProject also focuses on the Datagrid control.  I also enjoy answering Datagrid questions here at CodeProject, and around the web.  A common question that comes up involves grouping similar data, and providing a visual cue to the user when a repeating data element has changed.

The Standard Datagrid

In a typical Datagrid, all columns are treated "equally".  For example, you may wish to display Sales by Date, and to meet that end, you might include an ORDER BY Date clause.  However, if the end user is primarily interested in seeing how these sales vary by date, then this standard implementation might not make that obvious enough to them, as shown:

Standard Sales Grid

The Separated Datagrid

A better approach might be to add a separator row between each new group of sales for a given day, as seen at the top of the article.  To do that, take advantage of two Datagrid events, ItemDataBound, and PreRender.  We'll also need two variables public to the page:

    Public LastDateValue As DateTime = Convert.ToDateTime("1/1/1901")
    Public NewValues(100) As String

ItemDataBound

During the grid's ItemDataBound event, detect whether the current row has a SalesDate that varies from the previous row.  If it is different, store the value in the NewValues array, and update the public variable for the LastDateValue.  You could also do some other manipulation here during the ItemDataBound event.  For example, if you wanted to also display a total for each date, that would be calculated during this event.

Private Sub dgSales_ItemDataBound(ByVal sender As Object, _
          ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) _
Handles dgSales.ItemDataBound 'Here we need to detect when a row has a new SalesDate, and add
'it to our array
If e.Item.ItemType = ListItemType.Item Or _
e.Item.ItemType = ListItemType.AlternatingItem Then NewValues(e.Item.ItemIndex) = "" If e.Item.DataItem("SalesDate") <> LastDateValue Then LastDateValue = e.Item.DataItem("SalesDate") NewValues(e.Item.ItemIndex) = String.Format("{0:D}", _
e.Item.DataItem("SalesDate")) End If End If End Sub

PreRender

First off, I'm a fan of casting sender back to a Datagrid, and working with that rather than simply referring to the Datagrid by its ID.  That makes it easier if you ever copy/paste this code to another Datagrid---errr, I mean, if you move this code into a reusable component--yeah, that's what I meant.  Anyway.  You're already aware that the Datagrid ultimately renders as a <table> in HTML, but you may not have realized that you can access that table on the server-side using DG.Controls(0).  This table object is useful for several last-minute formatting tricks, including this one.

    Private Sub dgSales_PreRender(ByVal sender As Object, _
ByVal e As System.EventArgs) _ Handles dgSales.PreRender 'Just before the Datagrid renders its output, add the extra
'separator rows
Dim DG As DataGrid = CType(sender, DataGrid) Dim Tbl As Table = DG.Controls(0) Dim DGI As DataGridItem Dim Cell As TableCell Dim i As Integer, iAdded As Integer = 0 For i = 0 To NewValues.GetUpperBound(0) If NewValues(i) <> "" Then 'Just so it picks up the formatting class for my Header 'could have used ListItemType.Item DGI = New DataGridItem(0, 0, ListItemType.Header) Cell = New TableCell Cell.ColumnSpan = 3 Cell.Text = NewValues(i) DGI.Cells.Add(Cell) 'Add one to skip past the Header item Tbl.Controls.AddAt(i + iAdded + 1, DGI) iAdded = iAdded + 1 End If Next End Sub

Conclusion

With a few tricks, the Datagrid can help provide rich information to your client user base.  Don't by limited by the standard out-of-the-box output from this control - use the Datagrid's events to format the output to your heart's desire, and provide a more useful user interface.

An Alternate Approach

This problem can also be solved by nesting another Datagrid within the main Datagrid, binding the outer grid to a list of dates, and the inner grid to the sales, filtered for that date.  I may cover this technique in a future article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Marcie Jones


Member
Marcie runs DatagridGirl.com[^], a resource site for the ASP.NET Datagrid control, and now GridViewGirl.com[^] for ASP.NET 2.0.

Location: United States United States

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 42 (Total in Forum: 42) (Refresh)FirstPrevNext
GeneralMy vote of 1 Pinmemberlulintaous20:50 15 Jun '09  
GeneralItemIndex seems to be oiut of line when grid separator rows are added Pinmembermctears3:04 28 Nov '07  
QuestionDatagrid validation Pinmemberramvara3:27 5 Oct '07  
GeneralINSERT VALUE IN SHOPPING CART PinmemberG.GENOVESE7:23 24 Feb '06  
GeneralLittle help with a Datagrid Pinmemberjoe-black23:27 29 Nov '05  
GeneralRe: Little help with a Datagrid PinsitebuilderMarcie Jones17:24 30 Nov '05  
GeneralRe: Little help with a Datagrid Pinmemberjoe-black21:03 1 Dec '05  
GeneralWell, it doesn't seem to work when you don't auto generate columns PinmemberAlexander Yermakov12:15 21 Sep '05  
GeneralRe: Well, it doesn't seem to work when you don't auto generate columns PinsitebuilderMarcie Jones2:17 22 Sep '05  
QuestionWindows datagrid PinmemberMukund Pujari3:24 5 Sep '05  
GeneralRemoving Rows Pinmembermoquif6:41 18 May '05  
GeneralRe: Removing Rows Pinmembermoquif9:52 18 May '05  
GeneralYour thoughts to my approach .. PinsussvMike116:31 20 Dec '04  
Generaltable cell not getting added in the prerender stage Pinmemberhost5415:53 16 Nov '04  
GeneralRe: table cell not getting added in the prerender stage Pinmemberxlg22:14 28 Feb '05  
GeneralRe: table cell not getting added in the prerender stage Pinsussmichael ba10:38 10 Mar '05  
GeneralRe: table cell not getting added in the prerender stage Pinmemberxlg23:31 10 Mar '05  
GeneralRe: table cell not getting added in the prerender stage Pinmemberjoshihybrid11:38 28 Mar '05  
GeneralRe: table cell not getting added in the prerender stage PinmemberRRRoamer11:15 5 May '05  
GeneralPostback Losses Rows??? PinmemberABTCABE10:43 13 Aug '04  
Generalstrange error Pinmemberjimg7220:27 11 Aug '04  
GeneralViewState PinmemberFernando Finelli5:49 23 Jul '04  
GeneralNice - including simple version PinmemberParrotBoy1:06 22 Jul '04  
GeneralFixing Wrapping in DataGrid with AutoGenerateColumns PinmemberChuck Lane12:10 17 Jun '04  
Generalseparators and viewstate Pinmemberklugilbvjh4:51 23 Apr '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Feb 2004
Editor: Marcie Jones
Copyright 2004 by Marcie Jones
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project