In this article, I will show you how to manually sort the GridView WebControl and display sort direction arrows. The GridView has built-in sorting capabilities, however if we want visual feedback as to what column is being sorted and to what direction, we have to perform this ourselves. While extending the GridView WebControl would be optimal, I'm going to show a quick way to get it done without creating a new GridView control. Maybe in a future post I'll show how we can create a custom GridView control with sort arrows. Here is a picture of what our final sorted GridView will look like.
Here is the HTML markup of our GridView:
<asp:GridView
ID="GridView1"
runat="server"
AutoGenerateColumns="False"
DataKeyNames="CustomerID"
CssClass="gridview"
RowStyle-CssClass="gridview_itm"
AlternatingRowStyle-CssClass="gridview_aitm"
HeaderStyle-CssClass="gridview_hdr"
PagerStyle-CssClass="gridview_pgr">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="CustomerID_SortLnkBtn" runat="server" Text="Customer ID:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CustomerID" CausesValidation="false" />
<asp:ImageButton ID="CustomerID_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CustomerID" CausesValidation="false" />
</HeaderTemplate>
<ItemTemplate><%#Eval("CustomerID")%></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="CompanyName_SortLnkBtn" runat="server" Text="Company Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CompanyName" CausesValidation="false" />
<asp:ImageButton ID="CompanyName_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="CompanyName" CausesValidation="false" />
</HeaderTemplate>
<ItemTemplate><%#Eval("CompanyName")%></ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:LinkButton ID="ContactName_SortLnkBtn" runat="server" Text="Contact Name:" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="ContactName" CausesValidation="false" />
<asp:ImageButton ID="ContactName_SortImgBtn" runat="server" Visible="false" ToolTip="Click to Sort Column" CommandName="Sort" CommandArgument="ContactName" CausesValidation="false" />
</HeaderTemplate>
<ItemTemplate><%#Eval("ContactName")%></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The first step is to acquire customers from the Northwind database in the form of a DataTable. We will then acquire a DataView object from our DataTable, and sort the view. Once the data in our DataView has been sorted, we will then bind the GridView to the sorted DataView. To accomplish the data retrieval, sorting, and data binding, I've created the following method:
Private Sub GridView1_DataBind()
Dim dt As DataTable = New DataTable()
'fill our datatable w/ customers from the DB
Using conn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString)
Dim sql As String = "SELECT [CustomerID], [CompanyName], [ContactName] FROM [Customers] WITH (NOLOCK)"
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
Dim reader As SqlDataReader = Nothing
Try
conn.Open()
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
dt.Load(reader)
Finally
If Not reader Is Nothing AndAlso Not reader.IsClosed Then
reader.Close()
End If
End Try
End Using
If dt.Rows.Count > 0 Then
'get a dataView object from our dataTable of customers
Dim dv As DataView = dt.DefaultView
'if the user has elected to sort the gridview
If Not String.IsNullOrEmpty(Me.SortBy("GridView1")) Then
'get the sort expression and apply it to our dataView
Dim sortExpr As String = Me.SortBy("GridView1") & " " & IIf(Me.SortDirection("GridView1") = WebControls.SortDirection.Ascending, "ASC", "DESC").ToString()
dv.Sort = sortExpr
End If
'bind the dataView to our GridView
Me.GridView1.DataSource = dv
Me.GridView1.DataBind()
End If
End Sub
The logic is pretty straight forward. Take note to line 28. I am using 2 properties to store what column I am sorting by and what direction it is being sorted. I persist the values in the ViewState and I also pass what GridView I either want to retrieve or store values for. This allows me to have more that 1 sorting GridView on my page at a time using the same 2 properties. Here's the code for the 2 properties to assist us with sorting.
''' <summary>
''' Gets or sets the column name to be sorted.
''' </summary>
''' <param name="GridViewID">The unique ID of the GridView.</param>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private Property SortBy(ByVal GridViewID As String) As String
Get
Dim o As Object = ViewState(GridViewID & "_SortBy")
If Not o Is Nothing Then
Return o.ToString()
Else
Return String.Empty
End If
End Get
Set(ByVal value As String)
ViewState(GridViewID & "_SortBy") = value
End Set
End Property
''' <summary>
''' Gets or sets the sort direction.
''' </summary>
''' <param name="GridViewID">The unique ID of the GridView.</param>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Private Property SortDirection(ByVal GridViewID As String) As SortDirection
Get
Dim o As Object = ViewState(GridViewID & "_SortDirection")
If Not o Is Nothing Then
Return DirectCast(o, SortDirection)
Else
Return WebControls.SortDirection.Ascending
End If
End Get
Set(ByVal value As SortDirection)
ViewState(GridViewID & "_SortDirection") = value
End Set
End Property
We have the sort by and sort direction properties (storing/persistance mechanisms). We have the data retrieval, sorting of the data, and data binding method in place. Now what we have to do is think about what events we need to account for. First, on initial page load we'll want to fetch customer data and bind it to our GridView. We'll only want to bind our GridView the first time the page loads and not subsequent postbacks.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
'bind the gridview on page first load
GridView1_DataBind()
End If
End Sub
Now we are ready to make the magic happen. We want to handle the GridView's RowDataBound event and either show or hide our up/down arrows if the user has elected to sort a column.
Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
'if the row being dataBound is the header row - toggle sort image visibility/directions
If e.Row.RowType = DataControlRowType.Header Then
ToggleSortArrows(e.Row, "GridView1")
End If
End Sub
Private Sub ToggleSortArrows(ByVal headerRow As GridViewRow, ByVal gridViewID As String)
Dim sortImgBtn As ImageButton = Nothing
'loop through each cell in the header row
For Each tc As TableCell In headerRow.Cells
'loop through each control in the cell
For Each c As Control In tc.Controls
'if the control is an image button and is our sort image button
If TypeOf c Is ImageButton AndAlso c.ID.EndsWith("SortImgBtn") Then
sortImgBtn = DirectCast(c, ImageButton)
'if the image button is in the column being sorted
If Me.SortBy(gridViewID) = sortImgBtn.ID.Split(CChar("_"))(0) Then
'show the image button and set its image url (sorted column)
sortImgBtn.Visible = True
If Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending Then
sortImgBtn.ImageUrl = "~/img/uparrow.gif"
Else
sortImgBtn.ImageUrl = "~/img/dnarrow.gif"
End If
Else
'hide the image button (not a sorted column)
sortImgBtn.Visible = False
End If
End If
Next
Next
End Sub
Basically what we are doing is detecting if the row being DataBound is the header row or not. If it is, we want to loop through each cell in the header row and get a handle on the column's associated sort image. We use the ID of the sort image to acquire what column it represents and compare it to our SortBy property. If it matches, then we want to show the appropriate sort direction image. We hide the other sort images in non-sorted columns.
The only task we have left to account for is how to fire our sorting event. Take a quick look at our GridView HTML markup. The header row has both a LinkButton and ImageButton that raise a GridView command event to which we pass the column name that the user wants to sort by. We then handle the event in our code behind.
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles GridView1.RowCommand
If e.CommandName.ToUpper = "SORT" Then
InitializeSort(e.CommandArgument, "GridView1")
GridView1_DataBind()
End If
End Sub
Private Sub InitializeSort(ByVal sortBy As String, ByVal gridViewID As String)
If Me.SortBy(gridViewID) = sortBy Then
If Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending Then
Me.SortDirection(gridViewID) = WebControls.SortDirection.Descending
Else
Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending
End If
Else
Me.SortBy(gridViewID) = sortBy
Me.SortDirection(gridViewID) = WebControls.SortDirection.Ascending
End If
End Sub
Once we capture our sort row command, we initialize our SortBy and SortDirection properties. We either toggle the direction of the sorted column or the sorted column is a new column to be sorted to which we default the column to be sorted Ascending.
I hope this article helped a bit. It's a quick way to get a GridView sorted with visual indicators (sort arrows) without creating a new custom GridView control.
GridViewSorting_Soln.zip (90.61 kb)