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
If DataGrid1.Attributes("SortExpression") Is Nothing Then
DataGrid1.Attributes("SortExpression") = "LastName"
DataGrid1.Attributes("SortDirection") = "ASC"
End If
BindDataGrid()
End If
End Sub
Private Sub BindDataGrid()
Dim cn As SqlConnection
Dim cmdSelect As SqlCommand
cn = New SqlConnection("Server=amandrek;UID=sa;PWD=;Database=Northwind")
Dim strSQL As String = "Select * From employees"
Dim da As New SqlDataAdapter(strSQL, cn)
Dim ds As New DataSet()
da.Fill(ds, "Table1")
Dim dv As DataView = ds.Tables(0).DefaultView
Dim SortExpression As String = DataGrid1.Attributes("SortExpression")
Dim SortDirection As String = DataGrid1.Attributes("SortDirection")
dv.Sort = SortExpression + " " + SortDirection
DataGrid1.DataSource = dv
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 SortExpression As String = e.SortExpression
Dim SortDirection As String = "ASC"
If SortExpression.Equals(DataGrid1.Attributes("SortExpression").ToString()) Then
If DataGrid1.Attributes("SortDirection").ToString().StartsWith("ASC") Then
SortDirection = "DESC"
Else
SortDirection = "ASC"
End If
End If
DataGrid1.Attributes("SortExpression") = SortExpression
DataGrid1.Attributes("SortDirection") = SortDirection
BindDataGrid()
End Sub