Using GridView controls to display data in ASP.NET
Part eight of an eight-part series of blogs

The gridview control is at the heart of every ASP.NET webpage, displaying rows of data and allowing you to add, edit and delete records. This lengthy blog explains how to master this complex control.

  1. An introduction to GridView Controls
  2. Traps to Avoid when using Gridviews
  3. Creating GridView Controls
  4. Formatting Gridviews
  5. Template Fields / Template Columns
  6. Conditional formatting (RowDataBound Events)
  7. You clicked on a Gridview? The RowCommand Event
  8. Sorting a Gridview (this blog)

This blog is part of a larger online ASP.NET online tutorial.  Wise Owl's main business is running classroom-based training courses - have a look at our other .NET courses.

Posted by Andy Brown on 24 September 2012

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Sorting a Gridview

Getting a gridview to sort correctly is simple if you're using a datasource, but more difficult if you're using data classes.

Although sorting sounds easy, it's actually one of the hardest things to achieve in gridviews not based on simple data sources.  If you're not comfortable with classes and data tables, I'd miss out sorting for now, and come back to it when you've learnt about maintaining state and user controls.

The Theory of Sorting

In theory, to get a gridview to sort you just tell ASP.NET to allow sorting, then set which fields each column should sort by.  First, here's how to allow sorting:

Allowing sorting for a gridview

Just set the gridview's AllowSorting property to true!


To set which sort field should be used for each column, set the SortExpression:

The sort expression set for two columns

Here the sort fields for the first two columns are Taskname and StatusSortOrder.

You can now click on any column to sort by it:

About to sort a column

Click on any column heading to sort by the column's sort expression.


If you're using data sources, that's the end of the story.  Unfortunately if you're using your own data classes to populate gridviews it is much harder (the price you pay for taking control of your own life?).

The Practice - Handling the Sorting Event

For our gridview you still set the AllowSorting and SortExpression properties as shown above, but you then have to handle the Sorting event in VB or C#.

The Gridview Sorting event

Double-click on this event to attach code to it.


Here's what the event-handler should look like in VB (the C# would be similar, but isn't shown here; sorry!):

#Region "Sorting"


Protected Sub grdList_Sorting(ByVal sender As Object, _

ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs _

) Handles gv.Sorting


'see subroutine for comments

SortGridView(e.SortExpression, gv)


End Sub


#End Region

So when a user sorts a gridview, we call a subroutine called SortGridView, passing in two arguments:

  1. the field we're sorting by; and
  2. the gridview being sorted.

Unfortunately, we now have to write the SortGridView function!

The rest of the code isn't that easy, although I've tried to explain everything in detail.  However, once you've set it up then sorting will be trivial for all future gridviews that you create.

Creating a New Class to Handle Sorting

Every page containing a gridview is going to want to handle sorting in the same way, so we'll create a new class to contain common code:

Creating a class

Right-click on the App_Code folder (if you don't have one, see my earlier blog on data classes for how to create one), and choose to add a new item.

Choose to create a class (I've called mine clsUserControl):

Creating new class

Call your new class clsUserControl, then choose Add.


Changing the Base Class for Web Pages

The code-behind for any web page begins like this:

Partial Class frmTask

Inherits System.Web.UI.Page

Change this so instead it looks like this:

Partial Class frmTask

Inherits clsUserControl

Now edit your clsUserControl class so that it begins like this:

Imports Microsoft.VisualBasic

Imports System.Data

Public Class clsUserControl

Inherits System.Web.UI.Page

What these changes have done is to make sure that each web page using gridviews is based on your class called clsUserControl, which in turn is based on the System.Web.UI.Page class. 

If you're not an expert in classes, just note that you can now add additional routines into clsUserControl, and these will be available to each and every page based on it.

The Code to Get Sorting Working

Here's the code we'll use to make sure that sorting works:

'this property is used to remember the SQL command used to

'display a gridview, so that we can sort it without

'having to go back to the original search form

Property dtGridView() As DataTable



Return CType(ViewState("dtGridView"), DataTable)


Return Nothing

End Try

End Get

Set(ByVal value As DataTable)

ViewState("dtGridView") = value

End Set

End Property

Sub SetSortOrder(ByVal ThisSortFieldName As String)

If ThisSortFieldName = SortFieldName Then

If SortOrder = "ASC" Then

SortOrder = "DESC"


SortOrder = "ASC"

End If


SortOrder = "ASC"

End If

SortFieldName = ThisSortFieldName

End Sub

Public Property SortFieldName() As String


Return Convert.ToString(ViewState("SortFieldName"))

End Get

Set(ByVal value As String)

ViewState("SortFieldName") = value

End Set

End Property

Public Property SortOrder() As String


Return Convert.ToString(ViewState("SortOrder"))

End Get

Set(ByVal value As String)

ViewState("SortOrder") = value

End Set

End Property

Sub SortGridView(ByVal SortExpression As String, ByRef grd As GridView)


'If you use a DataSourceId for a gridview, can sort

'just by setting e.SortExpression.


'Otherwise, have to rebind gridview to original

'data source. To do this,

'just use the original querystring remembered

'in viewstate at time gridview was first displayed



Dim dt As DataTable = dtGridView

Dim dv As New DataView(dt)

dv.Sort = SortFieldName & " " & SortOrder

grd.DataSource = dv



End Sub

What this code does is to remember in something called ViewState (see a later part of this blog on maintaining state for more on what this means) to remember:

  • the field being sorted by (SortFieldName);
  • the sort order - ascending or descending (SorOrder); and
  • the data table underlying the data (dtGridView).

There may well be a much easier way to accomplish this, in which case I'd love to hear from you!  I've never found it ...

Final Stage - Remembering the Data for the GridView

None of the above will work if you don't tell the underlying class which data is being used, so that you can remember this in viewstate and retrieve it when necessary:

dtGridView = dtTasks

In this case, dtTasks will be the data table containing the tasks to be displayed.

If you're not sure where to put this, I'd recommend ignoring this page on sorting until you've also learnt about maintaining state and user controls, then you can see how it works in the final all-singing, all-dancing system.  And it's maintaining state which will be the subject of the next part of this blog series.

This blog has 0 threads Add post