ASP.Net Gridview Sorting using VB.Net

Updated on 03 Sep 2012,
Published on 23 Jun 2010

The ASP.Net also provides the sorting feature in GridView Control. You can sort the records in ascending or descending order retrieved from sql database. You can use VB.Net code to bind the SQL data with GridView control and follow the following simple steps to make your ASP.Net GridView control with sorting enabled. 

First of all drag the GridView control from Data controls menu.

<asp:GridView id="GridView1" runat="server">
</asp:GridView>

It will add the GridView control HTML source code as given above. Now click on GridView control to load the control properties at right side panel.

To allow the sorting in GridView control select True from the dropdown list of AllowSorting property of Gridview as shown in above image.

This will add AllowSorting="True" in HTML source code of GridView Control.

Next step is to bind the Sorting event for GridView Control.

To bind the Sorting event of GridView control, double click on the Sorting event in the properties viewer of GridView. This will add the Sorting event in the HTML source code and VB.Net code for Gridview.

HTML Source code for GridView Sorting

<asp:GridView 
    ID="GridView1" 
    runat="server" 
    AllowSorting="True" 
    OnSorting="GridView1_Sorting"
    AutoGenerateColumns="False" 
    CellPadding="5">
    <Columns>
        <asp:BoundField 
            DataField="productid" 
            SortExpression="productid" 
            HeaderText="Product ID"
            HeaderStyle-HorizontalAlign="Left" />
        <asp:BoundField 
            DataField="productname" 
            SortExpression="productname" 
            HeaderText="Product"
            HeaderStyle-HorizontalAlign="Left" />
        <asp:BoundField 
            DataField="unitprice" 
            SortExpression="unitprice" 
            HeaderText="Price"
            HeaderStyle-HorizontalAlign="Left" />
    </Columns>
</asp:GridView>

VB.Net Code for GridView Sorting in ASP.Net

Import the following namespaces to work with SQL database:

Imports System.Data
Imports System.Data.SqlClient[/code]

The above namespaces will allow you to access the SqlConnection, SqlCommand, SqlAdapter classes which provide the functionality to connect the SQL database and fetch the records from the specified table as in the following VB.Net code:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ViewState("sortOrder") = ""
        bindGridView("", "")
    End If
End Sub

Public Sub bindGridView(ByVal sortExp As String, ByVal sortDir As String)
    ' string variable to store the connection string
    ' defined in appsettings section of web.config file.
    Dim connStr As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString

    ' object created for SqlConnection Class.
    Dim mySQLconnection As New SqlConnection(connStr)

    ' if condition that can be used to check the sql connection
    ' whether it is already open or not.
    If mySQLconnection.State = ConnectionState.Closed Then mySQLconnection.Open()

    Dim mySqlCommand As New SqlCommand("select * from products", mySQLconnection)
    Dim mySqlAdapter As New SqlDataAdapter(mySqlCommand)
    Dim myDataSet As New DataSet()
    mySqlAdapter.Fill(myDataSet)

    Dim myDataView As New DataView()
    myDataView = myDataSet.Tables(0).DefaultView

    If Not String.IsNullOrEmpty(sortExp) Then
        myDataView.Sort = String.Format("{0} {1}", sortExp, sortDir)
    End If

    GridView1.DataSource = myDataView
    GridView1.DataBind()

    ' if condition that can be used to check the sql connection
    ' if it is open then close it.
    If mySQLconnection.State = ConnectionState.Open Then mySQLconnection.Close()
End Sub

Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
    bindGridView(e.SortExpression, sortOrder)
End Sub

Public Property sortOrder() As String
    Get
        If ViewState("sortOrder").ToString() = "desc" Then
            ViewState("sortOrder") = "asc"
        Else
            ViewState("sortOrder") = "desc"
        End If
        Return ViewState("sortOrder").ToString()
    End Get
    Set(ByVal value As String)
        ViewState("sortOrder") = value
    End Set
End Property

Output:

Get the output for above discussed code from the following link:

VB.Net GridView Sorting

Continue to next tutorial: Create ASP.Net Dynamic Gridview Control using VB.Net to learn how to add the gridview control and binding the data to it programmatically.

5 Responses to "ASP.Net Gridview Sorting using VB.Net"
clm
Good solution, thanks
Rohini
I like it very much.I is what exactly I needed from the day beginning till 2.24 PM.I found it and I have Worked out it .I got the Same result as the result in the output page.Thank you a lot............
Rohini
I like it very much.I is what exactly I needed from the day beginning till 2.24 PM.I found it and I have Worked out it .I got the Same result as the result in the output page.Thank you a lot............
ahmed mehmood
Awesome tutorial. Thank you sharing :)
MP
This was great! Worked just fine with my stored procedure. But, just one question if that's ok, how to bind the grid when changing the page of the grid, or when I have updated a row in the grid? How can I still have the same sortorder?
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers