In this article we sort the columns when user
clicks on Header. To do that we drag and drop a GridView control on the asp. net
form and bind the data with the GridView control. After that we have specified
OnSorting event and AllowSorting=true to the GridView.
GridView looks like the below figure1.

Figure1
.aspx code
<asp:GridView ID="GridView1" runat="server" OnSorting="SortRecords" AllowSorting="True" CellPadding="4" >
</asp:GridView>
Now add the following .VB code.
Imports
System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal
sender As Object,
ByVal e As
System.EventArgs)
Handles Me.Load
If Not
IsPostBack Then
BindData()
End If
End Sub
Private Sub BindData()
GridView1.DataSource =
Me.GetData()
GridView1.DataBind()
End Sub
Protected Sub SortRecords(ByVal
sender As Object,
ByVal e As GridViewSortEventArgs)
Dim sortExpression As String = e.SortExpression
Dim direction As String = String.Empty
If SortDirection = SortDirection.Ascending
Then
SortDirection =
SortDirection.Descending
direction = " DESC"
Else
SortDirection =
SortDirection.Ascending
direction = " ASC"
End If
Dim table As DataTable = Me.GetData()
table.DefaultView.Sort
= sortExpression & direction
GridView1.DataSource =
table
GridView1.DataBind()
End Sub
Public Property SortDirection()
As SortDirection
Get
If ViewState("SortDirection")
Is Nothing Then
ViewState("SortDirection")
= SortDirection.Ascending
End If
Return DirectCast(ViewState("SortDirection"),
SortDirection)
End Get
Set(ByVal value
As SortDirection)
ViewState("SortDirection")
= value
End Set
End Property
Private Function GetData()
As DataTable
Dim table As New DataTable()
Dim conn As New SqlConnection("Data
Source=.; uid=sa; pwd=Password$2; database=userinfo")
Dim sql As String = "SELECT * FROM Articletable"
Dim ad As New SqlDataAdapter(sql,
conn)
ad.Fill(table)
Return table
End Function
End Class
Now run the application.

Figure2
Now click on the Id, title, Description, Author columns to sort
the data in Ascending
or descending order.
Suppose we click on the Author column header to sort.

Figure3