|
Displaying Rows Grouped by Category
By:
Scott Mitchell
|
Created: 2003-05-13
|
Last Updated: 2003-07-25
|
Printer-Friendly Version
Imagine that you have a database table named
Given this table schema, imagine that we have the following records:
Now, imagine that you wanted to display the NBA players such that the players for each team
were grouped together. Clearly, a simple SQL query with an appropriate
Will return all the players playing for the Kings, followed by all the players playing for the Lakers, followed by all the players playing for the Spurs. Specifically, the results of the above SQL query, when run on the sample data, will be as follows:
Therefore, we could have a DataGrid display the name of each player, followed by their team name. However, what if we wanted the display to be a bit different. Rather than blandly list each player and his associated team, we want to list, in big bold letters, the name of the team, followed by all of its players. That is, we want the results to look something like:
Can we get a DataGrid to render this "style" of output? Sure, if we use a TemplateColumn and a bit of clever programming. We could also obtain such an appearance through the use of a master/detail-type DataGrid, which is discussed in detail in An Extensive Examination of the DataGrid Web Control: Part 14.
In using template, we can implement this sort of display through the use of a DataList and a custom function as well. For this FAQ, let's use the DataList approach.
Using a DataList to Display the Players, Grouped By Team
This DataList will display a table row and column for each player. Now, to display the team name, we need to be able to determine when the team name switches from one team to the next. That is, when we first start by displaying the players for the Kings, we want to emit the team name Kings and then the player's name, but then for each of the remaining players who play for the Kings, we only want to emit their name. When the first player for the next team (the Lakers) is displayed, again, we want to display both the team name and the player's name; however, for the remaining Lakers players we only want to display the player's name.
In the FAQ, Customizing the Appearance of a DataGrid Column Value,
we saw how to use a custom function to output a custom value based on the value of a
The following live demo shows this code in action. Note that you can add additional HTML around
the output of the team name in the
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Home | FAQs | Articles | About | My Blog | Buy the Book!
Copyright 2006, Scott Mitchell. All Rights Reserved.