How do I sorting in a gridview, cant get it to work

siraero

Active member
Joined
Jan 21, 2012
Messages
32
Programming Experience
Beginner
Hi.

I have a Gridview thats is working just fine, but when i click the sort header link, nothing happens !?? it will not sort the data by Desc or Asc

Can someone help...

Main grid_view code
VB.NET:
<asp:GridView ID="MySource" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="email_id" AllowPaging="True" emptydatatext="Ingen Data tilgængelig." allowsorting="true" EnableViewState="False" OnSorting="MySource_Sorting"  onRowDataBound="myGridView_RowDataBound">

My Code_Behind
VB.NET:
Imports System.IO
Imports System.Data
Imports System.Data.OleDb

Partial Class _default
    Inherits System.Web.UI.Page

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

    Public Sub bindGridView(sortExp As String, sortDir As String)

        'Get data from DB using DataSet 
        Using connection As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("MyConnStr").ConnectionString)
            Dim sql As String = "SELECT * FROM email_list"
            Using adapter As OleDbDataAdapter = New OleDbDataAdapter(sql, connection)
                Dim ds As New DataSet()
                adapter.Fill(ds)

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

                If sortExp <> String.Empty Then
                    myDataView.Sort = String.Format("{0} {1}", sortExp, sortDir)
                End If

                MySource.DataSource = ds
                MySource.DataBind()
            End Using
        End Using

    End Sub

    Protected Sub MySource_Sorting(sender As Object, e As 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(value As String)
            ViewState("sortOrder") = value
        End Set
    End Property

    Public Sub myGridView_RowDataBound(ByVal sender As Object, e As GridViewRowEventArgs)
        '*** EmailID ***'
        Dim lblEmailID As Label = CType(e.Row.FindControl("lblEmailID"), Label)
        If Not IsNothing(lblEmailID) Then
            lblEmailID.Text = e.Row.DataItem("email_id")
        End If

        '*** Name ***'
        Dim lblName As Label = CType(e.Row.FindControl("lblName"), Label)
        If Not IsNothing(lblName) Then
            lblName.Text = e.Row.DataItem("email_name")
        End If

        '*** Gen ***'
        Dim lblGen As Label = CType(e.Row.FindControl("lblGen"), Label)
        If Not IsNothing(lblGen) Then
            lblGen.Text = e.Row.DataItem("email_gen")
        End If

        '*** Old ***'
        Dim lblOld As Label = CType(e.Row.FindControl("lblOld"), Label)
        If Not IsNothing(lblOld) Then
            lblOld.Text = e.Row.DataItem("email_old")
        End If

        '*** Email ***'
        Dim lblEmail As Label = CType(e.Row.FindControl("lblEmail"), Label)
        If Not IsNothing(lblEmail) Then
            lblEmail.Text = e.Row.DataItem("email_adr")
        End If
    End Sub

End Class
 
Pretty sure you're going to need ViewState enabled.
 
Drop the "EnableViewState=False" from your gridview markup, or change it to true to ensure it's on.
 
The following example demonstrates how to use the AllowSorting property to enable sorting in a GridView control when automatically generated columns are used.

<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView AllowSorting Example</title>
</head>
<body>
<form id="form1" runat="server">

<h3>GridView AllowSorting Example</h3>

<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="true"
emptydatatext="No data available."
allowsorting="true"
runat="server">

</asp:gridview>

<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="CustomersSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>

</form>
</body>
</html>


The following example demonstrates how to use the AllowSorting property to enable sorting in a Gridview control when a Columns collection is defined. An image is also programmatically added to the header of the column being sorted to indicate the sort direction. You must provide your own images for this sample to work.
<%@ Page language="VB" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

Sub CustomersGridView_RowCreated(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

' Use the RowType property to determine whether the
' row being created is the header row.
If e.Row.RowType = DataControlRowType.Header Then

' Call the GetSortColumnIndex helper method to determine
' the index of the column being sorted.
Dim sortColumnIndex As Integer = GetSortColumnIndex()

If sortColumnIndex <> -1 Then

' Call the AddSortImage helper method to add
' a sort direction image to the appropriate
' column header.
AddSortImage(sortColumnIndex, e.Row)

End If

End If

End Sub

' This is a helper method used to determine the index of the
' column being sorted. If no column is being sorted, -1 is returned.
Function GetSortColumnIndex() As Integer

' Iterate through the Columns collection to determine the index
' of the column being sorted.
Dim field As DataControlField
For Each field In CustomersGridView.Columns

If field.SortExpression = CustomersGridView.SortExpression Then

Return CustomersGridView.Columns.IndexOf(field)

End If

Next

Return -1

End Function

' This is a helper method used to add a sort direction
' image to the header of the column being sorted.
Sub AddSortImage(ByVal columnIndex As Integer, ByVal row As GridViewRow)

' Create the sorting image based on the sort direction.
Dim sortImage As New Image()
If CustomersGridView.SortDirection = SortDirection.Ascending Then

sortImage.ImageUrl = "~/Images/Ascending.jpg"
sortImage.AlternateText = "Ascending Order"

Else

sortImage.ImageUrl = "~/Images/Descending.jpg"
sortImage.AlternateText = "Descending Order"

End If
' Add the image to the appropriate header cell.
row.Cells(columnIndex).Controls.Add(sortImage)

End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>GridView AllowSorting Example</title>
</head>
<body>
<form id="form1" runat="server">

<h3>GridView AllowSorting Example</h3>

<asp:gridview id="CustomersGridView"
datasourceid="CustomersSource"
autogeneratecolumns="false"
emptydatatext="No data available."
allowsorting="true"
onrowcreated="CustomersGridView_RowCreated"
runat="server">

<columns>
<asp:boundfield datafield="CustomerID"
headertext="Customer ID"
headerstyle-wrap="false"
sortexpression="CustomerID"/>
<asp:boundfield datafield="CompanyName"
headertext="CompanyName"
headerstyle-wrap="false"
sortexpression="CompanyName"/>
<asp:boundfield datafield="Address"
headertext="Address"
headerstyle-wrap="false"
sortexpression="Address"/>
<asp:boundfield datafield="City"
headertext="City"
headerstyle-wrap="false"
sortexpression="City"/>
<asp:boundfield datafield="PostalCode"
headertext="Postal Code"
headerstyle-wrap="false"
sortexpression="PostalCode" />
<asp:boundfield datafield="Country"
headertext="Country"
headerstyle-wrap="false"
sortexpression="Country"/>
</columns>

</asp:gridview>

<!-- This example uses Microsoft SQL Server and connects -->
<!-- to the Northwind sample database. Use an ASP.NET -->
<!-- expression to retrieve the connection string value -->
<!-- from the Web.config file. -->
<asp:sqldatasource id="CustomersSource"
selectcommand="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
connectionstring="<%$ ConnectionStrings:NorthWindConnectionString%>"
runat="server"/>

</form>
</body>
</html>
 
Back
Top