I have a Gridview populated with a DataTable that I store in the Session.
I'm trying to sort the columns, but have only been able to get it to
partially work. When I click on a header the first time it sorts as expected,
but thereafter doesn't do anything. I'm attempting to store the current sort
order in ViewState in order to determine what the order should be on a header
click. Can anyone see what I'm doing wrong?
I'm trying to sort the columns, but have only been able to get it to
partially work. When I click on a header the first time it sorts as expected,
but thereafter doesn't do anything. I'm attempting to store the current sort
order in ViewState in order to determine what the order should be on a header
click. Can anyone see what I'm doing wrong?
Code:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here
If Not (IsPostBack) Then
Dim dtUsers As New DataTable
Try
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("WilliganConnectionString").ConnectionString)
Dim cmd As New SqlCommand("stp_GetUsers", conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.HasRows Then
dtUsers.Load(reader)
Dim dvUsers As DataView = dtUsers.DefaultView
ViewState("SortOrder") = "lastName ASC"
Session("UsersTable") = dvUsers
grdUsers.DataSource = dvUsers
grdUsers.DataBind()
End If
reader.Close()
reader = Nothing
cmd.Dispose()
cmd = Nothing
conn.Dispose()
conn = Nothing
Catch ex As Exception
Trace.Warn(ex.ToString)
End Try
Else
'Only runs on first page load
grdUsers.HeaderRow.HorizontalAlign = HorizontalAlign.Center
End If
End Sub
Protected Sub grdUsers_Sort(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles grdUsers.Sorting
Dim dvUsers As New DataView()
dvUsers = Session("UsersTable")
Dim newSortDirection As String
If InStr(ViewState("SortOrder").ToString(), e.SortExpression.ToString
()) = 0 Then
newSortDirection = e.SortExpression.ToString() & " ASC"
Else
If InStr(ViewState("SortOrder").ToString(), "ASC") > 0 Then
newSortDirection = Replace(ViewState("SortOrder").ToString(),
"ASC", "DESC")
Else
newSortDirection = Replace(ViewState("SortOrder").ToString(),
"DESC", "ASC")
End If
End If
ViewState("SortOrder") = newSortDirection
Trace.Warn("viewstate sortorder before sorting" & ViewState
("SortOrder"))
dvUsers.Sort = ViewState("SortOrder").ToString()
grdUsers.DataSource = dvUsers
grdUsers.DataBind()
End Sub