要支持排序功能,只要将DataGrid Web 控件的AllowSorting 属性设为True,并且指定要排序时所要执行的程序为何即可。下列范例支持排序的功能,使用者可以点选欲排序的字段,该字段数据即以升幂方式排列;若再点选该字段一次,则该字段改成以降序的方式排列:
<%@Import Namespace=System.Data.ADO%>
<%@Import Namespace=System.Data%>
<!--#Include File="GetTable.inc"-->
<Html>
<Form Runat="Server">
<ASP:DataGrid Id="dgA" AllowPaging="True" PageSize="10"
OnPageIndexChanged="dgA_PageChg" Runat="Server"
PagerStyle-Mode="NumericPages" BorderColor="#808080"
HeaderStyle-Font-Names="Courier New"
HeaderStyle-BackColor="#D1DCEB"
HeaderStyle-HorizontalAlign="Center"
AllowSorting="True" OnSortCommand="dgA_Sort">
</ASP:DataGrid>
<ASP:TextBox Id="txtHidden" Runat="Server" Visible="False"
Enabled="False"/>
</Form>
<Script Language="VB" Runat="Server">
Dim dtDataTable As DataTable=GetTable("CH08\MyWeb.mdb", "Members")
Sub Page_Load(Sender As Object, e As EventArgs)
If Page.IsPostBack=False Then
txtHidden.Text="UserName"
dgA.DataSource=dtDataTable.DefaultView
Page.DataBind()
End If
End Sub
Sub dgA_PageChg(Sender As Object, e As DataGridPageChangedEventArgs)
If txtHidden.Enabled=True Then
dtDataTable.DefaultView.Sort=txtHidden.Text
Else
dtDataTable.DefaultView.Sort=txtHidden.Text & " Desc"
End If
dgA.DataSource=dtDataTable.DefaultView
Page.DataBind()
End Sub
Sub dgA_Sort(Sender As Object, e As DataGridSortCommandEventArgs)
If txtHidden.Enabled=False Then
dtDataTable.DefaultView.Sort=e.SortField
Else
dtDataTable.DefaultView.Sort=e.SortField & " Desc"
End If
txtHidden.Enabled=Not txtHidden.Enabled
txtHidden.Text=e.SortField
dgA.DataSource=dtDataTable.DefaultView
Page.DataBind()
End Sub
</SCRIPT>
</Html>
第一次点选时以升幂方式排序
第二次点选时以降序方式排序
文章来源于领测软件测试网 https://www.ltesting.net/