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 Page.IsPostBack Then
BindDataGrid("EmployeeID ASC")
End If
End Sub
Private Sub BindDataGrid(ByVal strSortField As String)
Dim cn As SqlConnection
Dim cmdSelect As SqlCommand
cn = New SqlConnection("Server=localhost;UID=sa;PWD=;Database=Northwind")
cmdSelect = New SqlCommand("Select * From employees Order By " & strSortField, cn)
cn.Open()
DataGrid1.DataSource = cmdSelect.ExecuteReader()
DataGrid1.DataBind()
cn.Close()
End Sub
Private Sub DataGrid1_SortCommand(ByVal source As Object, _
ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) _
Handles DataGrid1.SortCommand
Dim arrSortExpr() As String
Dim i As Integer
If e.SortExpression = "" Then Return
BindDataGrid(e.SortExpression)
arrSortExpr = Split(e.SortExpression, " ")
For i = 0 To DataGrid1.Columns().Count - 1
If (DataGrid1.Columns(i).SortExpression = e.SortExpression) Then
If UCase(arrSortExpr(1)) = "ASC" Then
arrSortExpr(1) = "DESC"
ElseIf UCase(arrSortExpr(1)) = "DESC" Then
arrSortExpr(1) = "ASC"
End If
DataGrid1.Columns(i).SortExpression = arrSortExpr(0) & " " & arrSortExpr(1)
Exit For
End If
Next
End Sub