Sorting GridView Manually!
By AzamSharp
Views: 43801

Introduction:

GridView control produces automatic sorting and paging behavior when bound to the SqlDataSource control. This is good news for developers who are using SqlDataSource. If you are using some other data source to populate the GridView you might need to add these features manually. In this article I will show you that how you can sort the columns of the GridView control when using a DataSet as the data source for the GridView.

Populating the GridView Control:

Let's first populate the GridView control with some data. In this article I will be using the Northwind database which is installed by default when you install SQL SERVER 7 or SQL SERVER 2000 database. Take a look at the code below which populates the GridView control.

private DataSet GetData()

{

SqlConnection myConnection = new SqlConnection(ConnectionString);

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

return ds;

}

As, you can see I am using simple DataSet container to populate the GridView control. Now, let's talk about sorting.

GridView HTML Code:

The first thing that you must notice is that I am not using any template columns in this article. The columns are generated automatically for the GridView control which are bound to the data source. Take a look at the HTML generated by the GridView control to have a clear picture.

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" OnSorting="GridView1_Sorting">

</asp:GridView>

The AllowSorting property has to be set to true so that it will render the GridView columns as links which can be clicked to fire the OnSorting event.

Sorting GridView Columns:

Sorting can be done in different ways but in this article I will show you that how you sort in ascending and descending order. The first thing you need to have is a property which returns you the sort direction. The sort direction represents that if the column has to be sorted in ascending or descending order. 

public SortDirection GridViewSortDirection

{

get

{

if (ViewState["sortDirection"] == null)

ViewState["sortDirection"] = SortDirection.Ascending;

return (SortDirection) ViewState["sortDirection"];

}

set { ViewState["sortDirection"] = value; }

}

The GridViewSortDirection is a simple property which returns the new sort direction for the GridView control. Since, the header of the column triggers a postback that is why I am saving the last sort direction into the ViewState object. Once, I know the last direction I can give the user the new sort direction. This means that if the column was sorted in ascending order then the new direction has to be descending.

Now, let's take a look at the GridView_OnSorting event which is fired when you click the header of the column to sort it.

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

{

string sortExpression = e.SortExpression;

if (GridViewSortDirection == SortDirection.Ascending)

{

GridViewSortDirection = SortDirection.Descending;

SortGridView(sortExpression, DESCENDING);

}

else

{

GridViewSortDirection = SortDirection.Ascending;

SortGridView(sortExpression, ASCENDING);

}

}

The first line gets the name of the column that is clicked. This means that if you clicked on the CategoryName column the e.SortExpression will contain "CategoryName". The code is pretty simple, I check that if the last sort direction is ascending if so, then I sort the data in descending order and vice versa. The SortGridView method is responsible for the actual sort. Take a look at the SortGridView method given below:

private void SortGridView(string sortExpression,string direction)

{

// You can cache the DataTable for improving performance

DataTable dt = GetData().Tables[0];

DataView dv = new DataView(dt);

dv.Sort = sortExpression + direction;

GridView1.DataSource = dv;

GridView1.DataBind();

}

The SortGridView method takes the sortExpression and the direction as the parameters. The GetData method gets the data from the database. At this point it is a good idea to put the DataTable object into a Cache object so you don't have to fetch the data from the database on each request. A DataView is created on the DataTable and is sorted using the sortExpression and the direction. Finally, the DataView object is used to populate the GridView. 

I hope you liked the article, happy coding!

 

 

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: Thanks
Name: Phil
Date: 2/9/2007 11:06:55 PM
Comment:
I have been troubled with this sorting problem for several day and now I CAN do it with your code.
Thanks!
Subject: Sorting problem
Name: Allan
Date: 3/8/2007 5:36:25 PM
Comment:
Hello,

Thanks for the code! I am one step closer.. However, I am experiencing the following problem: have a gridview with four columns. The columns which are initially descending can be clicked on and sorted without a problem. The columns which are initially ascending take two clicks to sort. The first click does not work, but the second click does. Every subsequent click after that works just fine. However, when I go back and forth between various columns (descending or ascending), it will always requires an extra click before it starts sorting again.
Subject: RE: Sorting Problem
Name: AzamSharp
Date: 3/12/2007 8:40:50 PM
Comment:
Hi Allan,

You may have to create a HashTable and store the state of each column. Something like:

Key Value
FirstName ASC
LastName DSC
SSN ASC

This will tell you the last sort action on the column and you will then sort it in the reverse direction.


Subject: Column
Name: Mike Martin
Date: 3/13/2007 8:33:22 PM
Comment:
I have a gridview that I would like to set the default sort to the ID column, which is set as an INT in the SQL DB. Can you point me in the right direction to set that up? Thanks for the help.
Subject: Sorting GridView Manually!
Name: Charles Evans
Date: 3/16/2007 11:45:54 AM
Comment:
error CS0103: The name 'DESCENDING' does not exist in the current context.
Sorry, I'm new to c#. What do I need to do?
Subject: ASCENDING and DESCENDING
Name: Shaun
Date: 3/28/2007 12:49:26 PM
Comment:
In order to get this working (Visual Web Developer 2005), I had to change the strings for ASCENDING and DESCENDING. Here is the method that works for me

-------------------------------


protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)

{

string sortExpression = e.SortExpression;

if (GridViewSortDirection == SortDirection.Ascending)

{

GridViewSortDirection = SortDirection.Descending;

SortGridView(sortExpression, " DESC");

}

else

{

GridViewSortDirection = SortDirection.Ascending;

SortGridView(sortExpression, " ASC");

}

}
Subject: confirm
Name: sudhir
Date: 4/17/2007 2:40:51 AM
Comment:
hi,
please explain it on the page.....

http://www.gridviewguy.com/ArticleDetails.aspx?articleID=176

SortGridView(sortExpression, DESCENDING);


SortGridView(sortExpression, ASCENDING);

what is DESCENDING? and what is ASCENDING?

give the code of pageload events.
Subject: sorting
Name: Tina
Date: 4/19/2007 10:09:17 PM
Comment:
Hi

The code is really very helpful...But i encounter one problem ...In the SortGridView Method,the line
dv.Sort= sortExpression+direction;
shows error...

For Eample if the column I want to sort is CustID,It says CustID Descending is not existing..If i repale it with
dv.Sort="CustID DESC",it works like a breeze...

Any suggestions will be helpful........
Subject: sorting
Name: Tina
Date: 4/19/2007 10:10:50 PM
Comment:
Hi

The code is really very helpful...But i encounter one problem ...In the SortGridView Method,the line
dv.Sort= sortExpression+direction;
shows error...

For Example if the column I want to sort is CustID,It says CustID Descending is not existing..If i replace it with
dv.Sort="CustID DESC",it works like a breeze...

Any suggestions will be helpful........
Subject: sorting
Name: Tina
Date: 4/20/2007 11:30:36 AM
Comment:
Hi

I got the answer for the previous mail...I just changed it:

dv.Sort= sortExpression+" "+direction;

and it worked.......
Thanks...
Subject: thanks
Name: Siva
Date: 4/26/2007 2:15:29 AM
Comment:
hi ,

thanks

Subject: about this article
Name: saran
Date: 5/8/2007 12:54:43 AM
Comment:
hai,
it is very good .This site also very excellent .carry on...

bye
regards
saravanan
Subject: Thanks
Name: Alex
Date: 5/14/2007 7:02:56 AM
Comment:
You have saved me from another sleepless night trying figure out how to sort a gridview. Many thanks!!
Subject: Realy help full
Name: Navin
Date: 5/28/2007 3:38:18 AM
Comment:
Hi,
Thanks this is realy help full to me.
Subject: Sorting Problem, No hashtable please
Name: Rogier
Date: 6/5/2007 12:33:07 PM
Comment:
If you have to click twice the very first time, add:
if (!IsPostBack)
{
GridViewSortDirection = SortDirection.Descending;
}
in the page_load.
Subject: not working
Name: hari
Date: 7/5/2007 12:16:46 PM
Comment:
Hi Every body,
I am facing the following problem.if I click the hyperlink in the column It is not going to onsorting event.
Any ideas?Please help me to resolve this issue
Subject: RE: Not Working
Name: AzamSharp
Date: 7/5/2007 5:27:30 PM
Comment:
Hi,

Check that if the events are attached properly.
Subject: sorting
Name: shiva
Date: 7/8/2007 11:59:40 PM
Comment:
I am new to gridview applications
in gridsort event
SortGridView(sortExpression, DESCENDING);
SortGridView(sortExpression, ASCENDING);
in this its is giving an error
DESCENDING doesnot exist in the current context
Subject: Gridview sorting
Name: ASiddiqui
Date: 7/31/2007 3:22:49 PM
Comment:
Can we sort the template column in the gridview?
Subject: .net
Name: sandya
Date: 8/17/2007 2:54:36 AM
Comment:
ok cool we want very clearly
Subject: feedback
Name: prashant
Date: 8/18/2007 2:36:40 AM
Comment:
Thanks a lot ur code solved my problm...


Subject: Thanks
Name: Roy
Date: 9/6/2007 9:31:59 AM
Comment:
As new learner to the .Net country and all it's backroads

This is a GodSend!!!!
Subject: Error: Can not find column [ColNameDesc/ColNameAsc]
Name: sasan
Date: 9/9/2007 2:03:39 AM
Comment:
This Code is very good,But I had problem at this part :
dv.Sort = sortExpression + direction;

and I got this error:
Error: Can not find column [ColNameDesc/ColNameAsc]

Later I channged this code to this one and works well:

dv.Sort = sortExpression +" "+ direction;
Subject: Answer to Allan Problem
Name: n
Date: 9/14/2007 9:10:03 AM
Comment:
First time u click any column it sorts it ascending by default(if not set otherwise) and second time decending ..third time again ascending....and so on...so if u have a column in which the data is sorted ascending by default...do not except it to sort decending first time u click it.
Subject: Thanks
Name: Madhu Menon
Date: 9/28/2007 2:13:20 AM
Comment:
Hi There,

The article is very nice. Its Excellent and simple.

No words, but
Thanks :)

Cheers
Menon
Subject: Easier Way
Name: iWay
Date: 10/2/2007 1:57:38 PM
Comment:
If you're like me and let GridView do its own sorting, there's an easier way to display Up Arrow/Down Arrow on the correct column.

After enabling:


And setting the Sort Expression on each Field:


Switch to Code and in the sub GridView1_RowDataBound add this code:
If e.Row.RowType = DataControlRowType.Header Then
Dim img As New Image
'determine if img should be up arrow or down arrow
If GridView1.SortDirection = SortDirection.Ascending Then
img.ImageUrl = "../pics/downarrow.gif"
ElseIf GridView1.SortDirection = SortDirection.Descending Then
img.ImageUrl = "../pics/uparrow.gif"
End If

'now determine which column to add arrow to
Select Case GridView1.SortExpression
Case "ClientName", ""
'GridView1.SortExpression is blank until header clicked
'so, put "" on default sorted column
e.Row.Cells(0).Controls.Add(New LiteralControl(" "))
e.Row.Cells(0).Controls.Add(img)
Case "City"
e.Row.Cells(1).Controls.Add(New LiteralControl(" "))
e.Row.Cells(1).Controls.Add(img)
Case "State"
e.Row.Cells(2).Controls.Add(New LiteralControl(" "))
e.Row.Cells(2).Controls.Add(img)
End Select
End If

each Case statement corresponds to the SortExpression on the field tag (Template or BoundField)
Subject: Thanks
Name: Raj
Date: 10/22/2007 4:07:18 AM
Comment:
Code sample is simple and very helpful.
Thanks a lot.
Raj
Subject: Thanks
Name: Gunjal
Date: 10/23/2007 3:58:27 AM
Comment:
I have been struggling with sorting problem since 2 days now I WILL BE ABLE TO SLEEP WELL

Thanks Again
Subject: GridVIew Sorting
Name: ramesh
Date: 10/29/2007 2:06:56 AM
Comment:
hi Azam,
Your article excellent. Thanks for the presentation.
Subject: gridview sorting
Name: john rieder
Date: 10/29/2007 11:46:41 AM
Comment:
used this method and it works great...I have to store the dataset in session and re-bind it in the grid_sorting method...but have a problem. My gridview uses dropdown lists filtered by data in the row where the ddl resides (do this in rowdatabound) when I 'sort' I lose my ddl data. Cannot get the rowdatabound to fire again? Any ideas?
Subject: jazakallah
Name: wajid ansari
Date: 11/12/2007 10:47:26 PM
Comment:
hi
thanks a lot for providind this code.
Subject: Look for a way to sort by weekdays
Name: Shruthi
Date: 11/15/2007 9:28:18 PM
Comment:
hi thanks for code ..
This helped a lot
Is there any way to sort grid by weekdays rather than ascending or descending, i mean to say ,i hav days column clickin on that column header it should sort according to week, like sunday, monday
again clickin on it should sort lik saturday, friday
Please suggest any ideas regarding this
Subject: Superb.....
Name: Pandiana
Date: 11/30/2007 3:13:14 AM
Comment:
The article is very fine for the beginners.. we are expecting more from the author....
Subject: Sorting GridView
Name: Rupesh Tiwari
Date: 12/2/2007 10:42:28 PM
Comment:
my gridview sortexpression="a"
it is showing me an error :
Cannot find column a descending
Subject: getdata() method
Name: heena
Date: 12/4/2007 11:07:07 AM
Comment:
thank you for this coding. its best solution for my problem but i still have a problem here with
DataTable dt = GetData().Tables[0]; in
Private void SortGridView{}

"There is no getdata() method with DataTable"

please guide me for that and thank you again
Subject: error at dv.Sort = sortExpression + direction;
Name: harshit
Date: 12/5/2007 4:11:31 AM
Comment:
replace
dv.Sort = sortExpression + irection;
by
dv.Sort = sortExpression + " "+direction;
Subject: good blog
Name: rigs
Date: 12/18/2007 12:09:20 AM
Comment:
very nice explanation..thanx...
Subject: Well explained
Name: Bino
Date: 1/3/2008 8:11:46 AM
Comment:
Nice article,well explained.

www.codepal.co.in
Subject: getdata()
Name: Jeff
Date: 1/15/2008 2:38:06 AM
Comment:
I am also not able to run this because it generates this error on compile:
The name 'GetData' does not exist in the current context

Is this function requiring a using statement? How do I include this?
Subject: Thanks
Name: Selva
Date: 1/22/2008 9:24:07 AM
Comment:
Really its very usfull.
Subject: good stuff
Name: Adam
Date: 2/7/2008 6:13:02 AM
Comment:
Thanks for the snippets. very clean, very nice... the only thing is... make sure you put a space between sortExpression and direction... so...

sortExpression + " " + direction
Subject: Thanks!
Name: Bob Johnson
Date: 2/12/2008 12:03:07 PM
Comment:
This was just what I needed. Thanks for the help!
Subject: LastColumnSorted
Name: Fred
Date: 2/13/2008 5:09:47 PM
Comment:
Hi, Thanks for the code.

I added one little thing to the code:

A LastColumnSorted property.

If the current column being sorted is not the last one then I default the sort order to Ascending.
Subject: Nested Gridview
Name: Dan
Date: 2/14/2008 6:30:38 AM
Comment:
Hello everybody,
I think I have an interesting question:
Does anybody knows a solution for using sorting within nested gridviews?
In this case I cannot set "global" variables like sortdirection or sortexpression,
because every grid needs a special one.
I am struggling for more than 2 days with this problem - please help me!
Thanks in advance.
Subject: nice one
Name: sanjeev kumar
Date: 2/15/2008 1:11:35 AM
Comment:
nice Tutorial
Subject: Getting Error
Name: Mohanraj.A
Date: 2/15/2008 5:34:17 AM
Comment:
Hi,
I am trying to use this example, i get an error "GridViewSortDirection.get': not all code paths return a value". Can u please help regarding this.
Subject: RE: Getting Error
Name: AzamSharp
Date: 2/15/2008 7:31:48 AM
Comment:
Hi Mohanraj.A, Make sure that the property is returning the value in the getter.
Subject: RE: Nested Gridview
Name: AzamSharp
Date: 2/15/2008 7:34:53 AM
Comment:
Hi Dan, I have never tried it but you would keep a record of each GridView sort direction. For this you can use a simple entity class which stores the id of the GridView and the sort direction.
Subject: Thanks with another Question
Name: Kamesh
Date: 2/19/2008 2:31:34 AM
Comment:
Hi,Your article was very much purposeful.

But,why is that u have chosen only a VIEWSTATE object.

Thankyou.
Subject: RE: Thanks with another Question
Name: AzamSharp
Date: 2/20/2008 8:46:53 PM
Comment:
Hi Kamesh, The ViewState object will maintain the state of the sort during the postback.
Subject: Another query:
Name: Kamesh
Date: 3/2/2008 6:00:52 AM
Comment:
Thanks for replying Azam ,

Another query:

Can we have multiple itemtemplates in a single Template Field


Subject: Thanks
Name: Klintz
Date: 3/14/2008 6:45:40 AM
Comment:
thanks for the code.
Subject: Thanks
Name: srinivas
Date: 3/25/2008 8:20:30 AM
Comment:
Thanks for your articles.
Subject: Sorting GridView
Name: Menon
Date: 3/26/2008 6:27:02 AM
Comment:
The Sorting works for me fine but only for specific Page. When i sort a column and then when i go to next page. The Sorting is gone. Can you please help me out with that?
Well on Paging i use GridView1.PageIndex = e.NewPageIndex;
GetData(); Thanks,
Menon
Subject: Thanks
Name: Mukesh
Date: 3/31/2008 2:34:35 AM
Comment:
I m not understanding the

SortGridView(sortExpression, DESCENDING);

Subject: Paging
Name: Bill
Date: 4/3/2008 8:27:06 AM
Comment:
Do you have an example of paging using this same methodology?

Thank You!
Subject: RE: Paging!
Name: AzamSharp
Date: 4/3/2008 2:39:38 PM
Comment:
Hi Bill, In paging you just need to implement the Selected_PageIndexChanging event.
Subject: Gridview Sorting with Image Symbol
Name: Utsav
Date: 4/3/2008 10:39:36 PM
Comment:
Nice Article
Subject: Paging & Sorting
Name: menon
Date: 4/14/2008 3:28:38 AM
Comment:
Hi Azam
Can you be please be more specific about Paging with this Sorting. I use GridView1.PageIndex = e.NewPageIndex;
GetData(); in my PageIndexChanging Method. But on Changing the Page i lose the Sorting.
Subject: Paging
Name: menon