Hi @WONG Tony ,
Maybe you can write it another way. For details, you can refer to the code below.
<asp:GridView ID="GridView1" runat="server" DataKeyNames="ID" AllowSorting="true" OnSorting="gridView_Sorting" OnSorted="GridView1_Sorted" />
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim constr As String = ConfigurationManager.ConnectionStrings("DBCS").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Test ")
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
ViewState("dirState") = dt
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Using
End Sub
Private Function ConvertSortDirectionToSql(ByVal column As String) As String
Dim sortDirection As String = "ASC"
Dim sortExpression As String = TryCast(ViewState("SortExpression"), String)
If sortExpression IsNot Nothing Then
If sortExpression = column Then
Dim lastDirection As String = TryCast(ViewState("SortDirection"), String)
If (lastDirection IsNot Nothing) AndAlso (lastDirection = "ASC") Then
sortDirection = "DESC"
End If
End If
End If
ViewState("SortDirection") = sortDirection
ViewState("SortExpression") = column
Return sortDirection
End Function
Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
Dim dataTable As DataTable = TryCast(GridView1.DataSource, DataTable)
If dataTable IsNot Nothing Then
Dim dataView As DataView = New DataView(dataTable)
dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortExpression)
GridView1.DataSource = dataView
GridView1.DataBind()
End If
End Sub
Protected Sub GridView1_Sorted(ByVal sender As Object, ByVal e As EventArgs)
GridView1.HeaderRow.Cells(0).Text = "GV sorted"
End Sub
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.