One of the common things people want to do when displaying data with grid controls is to have the little up and down arrows next to the header columns to indicated what direction the data is being sorted in. You see this in Windows Explorer and many other programs. This has been traditionally something that is difficult to do with the GridView control in ASP.NET. If you search the internet you will find a variety of hacks to do this:
Matt Berseth: Building a VS2008 Styled Grid with the GridView Control
4 Guys From From Rolla.com: Improving the Sort Arrows GridView Control
Some of these implementations have various limitations such as they don’t work if you use AutoGenerateColumns = true. In .NET 4 we addressed these problems by adding a couple of new properties to the GridView:
These allow you to easily set specific styles on both the header cells and the item cells of the GridView. Here is an example of this put to use in a GridView:
What this does in when the grid is being sorted the header of the grid the sortasc or sortdesc class will be applies to the header cell like this depending on the direction it is being sorted on:
<th style=”sortasc”>Column Header</th>
<th style=”sortdesc”>Column Header</th>
And I’ve got some simple CSS defined that will apply a sort arrow:
The end result will look like this showing the grid sorting each direction on the LastName column with nice arrows showing the direction.
I’ve created a sample of this you can download and try out: http://www.cshonline.com/aspnet/gridsortarrows.zip.
Another common request for the GridView deals with how it displays when there is no data. It basically does not display at all. You will basically see a set of empty <div></div> tags in the page. There is a template inside the Grid that you can use to display some text:
But a lot of the time what you really want is to display the header row of the Grid showing what COULD be displayed. Once again if you search around the Internet you might find hacks to show the header. Once again because this was a common ask we added support for this in .NET 4. You can now use the ShowHeaderWhenEmpty property to show the header. Here is what the markup would look like:
And here is what a GridView would display with no data with this property enabled:
Hopefully all of these new options will make using the GridView easier. Enjoy!