Sort The Columns Of Grid View In VB.NET

In this article we sort the columns when user clicks on Header link of GridView control.
  • 30651

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 image.


.aspx code

<asp:GridView ID="GridView1" runat="server" OnSorting="SortRecords" AllowSorting="True" CellPadding="4" >


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


        End If


    End Sub

    Private Sub BindData()


        GridView1.DataSource = Me.GetData()



    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"


            SortDirection = SortDirection.Ascending

            direction = " ASC"

        End If

        Dim table As DataTable = Me.GetData()

        table.DefaultView.Sort = sortExpression & direction

        GridView1.DataSource = table


    End Sub


    Public Property SortDirection() As SortDirection


            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)


        Return table

    End Function


End Class


Now run the application.


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.



More Articles

© 2020 DotNetHeaven. All rights reserved.