GridView Sorting

written by Ryan Olshan on Thursday, December 01 2005

I discovered that the GridView lacks a feature when it comes to sorting. What if you are using a DataSource such as SqlDataSource, but you don't want to sort the GridView using the same SelectCommand statement that was used to bind the GridView to its datasource? Using the OnSorting event of the GridView, you can add the below to execute when the OnSorting event is fired:

VB.NET
Protected Sub gridview_Sorting(ByVal
sender As Object, ByVal e As GridViewSortEventArgs)
   Dim
strSortDir As String = Nothing

   Select Case e.SortDirection
      Case SortDirection
.Ascending
         strSortDir =
"ASC"


      Case SortDirection
.Descending
         strSortDir =
"DESC"

  
End Select

   sqlDataSource.SelectCommand = "SET NOCOUNT ON;SELECT Row FROM Table WHERE SomeCondition='Something' ORDER BY " & e.SortExpression & " " & strSortDir
End Sub

C#
protected
void gridview_Sorting(object sender, GridViewSortEventArgs
e)
{
   string strSortDir = null;

   switch (e.SortDirection)
   {
      case SortDirection
.Ascending:
         strSortDir = "ASC"
;
         break
;

      case SortDirection
.Descending:
         strSortDir = "DESC"
;
         break
;
   }

   sqlDataSource.SelectCommand = "SET NOCOUNT ON;SELECT Row FROM Table WHERE SomeCondition='Something' ORDER BY " + e.SortExpression + " " + strSortDir;
}

Note: sqlDataSource is the ID of the SqlDataSource control.

R

Kick this post on .NET Kicks

Similar Posts

  1. VB.NET GridView Sorting/Paging w/o a DataSourceControl DataSource
  2. GridView without DataSourceControl DataSource
  3. C# GridView Sorting/Paging w/o a DataSourceControl DataSource

Post a comment