实现 DataGird 的升序和降序排列
代码如下:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not IsPostBack Then
If dgdBook.Attributes("SortExpression") Is Nothing Then
dgdBook.Attributes("SortExpression") = "dlh" '这里给datagrid增加一个排序属性,且默认排序表达式为dlh
dgdBook.Attributes("SortDirection") = "ASC" '这里给datagrid增加一个排序方向属性,且默认为升序排列
End If
BindDataGrid()
End If
End Sub
Private Sub BindDataGrid()
'..
Dim dt As New DataTable
dataAdapter.Fill(dt)
Dim dv As DataView = dt.DefaultView
Dim SortExpression As String = dgdBook.Attributes("SortExpression") '排序表达式
Dim SortDirection As String = dgdBook.Attributes("SortDirection") '排序方向
dv.Sort = SortExpression + " " + SortDirection '指定视图的排序方式;
dgdBook.AllowSorting = True
dgdBook.DataSource = dv
dgdBook.DataBind()
End Sub
Private Sub dgdBook_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgdBook.SortCommand
Dim SortExpression As String = dgdBook.Attributes("SortExpression").ToString '获取原来的排序字段
Dim SortDirection As String = dgdBook.Attributes("SortDirection").ToString '获取原来的排序方向
If e.SortExpression.ToString = SortExpression Then
SortDirection = IIf(SortDirection = "ASC", "DESC", "ASC") '点击同一列标题改变排列方向
Else '点击不同列标题改变排列字段,升序排序
SortExpression = e.SortExpression.ToString
SortDirection = "ASC"
End If
dgdBook.Attributes("SortExpression") = SortExpression '赋予新的排序字段
dgdBook.Attributes("SortDirection") = SortDirection '赋予新的排序方向
BindDataGrid()
End Sub
If Not IsPostBack Then
If dgdBook.Attributes("SortExpression") Is Nothing Then
dgdBook.Attributes("SortExpression") = "dlh" '这里给datagrid增加一个排序属性,且默认排序表达式为dlh
dgdBook.Attributes("SortDirection") = "ASC" '这里给datagrid增加一个排序方向属性,且默认为升序排列
End If
BindDataGrid()
End If
End Sub
Private Sub BindDataGrid()
'..
Dim dt As New DataTable
dataAdapter.Fill(dt)
Dim dv As DataView = dt.DefaultView
Dim SortExpression As String = dgdBook.Attributes("SortExpression") '排序表达式
Dim SortDirection As String = dgdBook.Attributes("SortDirection") '排序方向
dv.Sort = SortExpression + " " + SortDirection '指定视图的排序方式;
dgdBook.AllowSorting = True
dgdBook.DataSource = dv
dgdBook.DataBind()
End Sub
Private Sub dgdBook_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgdBook.SortCommand
Dim SortExpression As String = dgdBook.Attributes("SortExpression").ToString '获取原来的排序字段
Dim SortDirection As String = dgdBook.Attributes("SortDirection").ToString '获取原来的排序方向
If e.SortExpression.ToString = SortExpression Then
SortDirection = IIf(SortDirection = "ASC", "DESC", "ASC") '点击同一列标题改变排列方向
Else '点击不同列标题改变排列字段,升序排序
SortExpression = e.SortExpression.ToString
SortDirection = "ASC"
End If
dgdBook.Attributes("SortExpression") = SortExpression '赋予新的排序字段
dgdBook.Attributes("SortDirection") = SortDirection '赋予新的排序方向
BindDataGrid()
End Sub