对DataGrid控件中的列进行排序的例子
1<HTML>
2 <HEAD>
3 <title>DataGridSort.aspx</title>
4 <script runat="server">
5
6void Page_Load(Object sender , EventArgs e)
7{
8 if (! IsPostBack ) {
9 BindDataGrid( "Title" );
10 }
11}
12
13void BindDataGrid( string strSortField ) {
14 SqlConnection conPubs;
15 SqlCommand cmdSelect;
16
17 conPubs = new SqlConnection( @"Server=localhost;Integrated Security=SSPI;Database=Pubs" );
18
19 cmdSelect = new SqlCommand( "Select * From Titles Order By " + strSortField, conPubs );
20 conPubs.Open();
21 dgrdTitles.DataSource = cmdSelect.ExecuteReader();
22 dgrdTitles.DataBind();
23 conPubs.Close();
24}
25
26void dgrdTitles_SortCommand( object s, DataGridSortCommandEventArgs e ) {
27 BindDataGrid( e.SortExpression );
28}
29
30 </script>
31 </HEAD>
32 <body>
33 <form Runat="Server">
34 <asp:DataGrid ID="dgrdTitles" AllowSorting="True" OnSortCommand="dgrdTitles_SortCommand" CellPadding="10"
35 Runat="Server" />
36 </form>
37 </body>
38</HTML>
2 <HEAD>
3 <title>DataGridSort.aspx</title>
4 <script runat="server">
5
6void Page_Load(Object sender , EventArgs e)
7{
8 if (! IsPostBack ) {
9 BindDataGrid( "Title" );
10 }
11}
12
13void BindDataGrid( string strSortField ) {
14 SqlConnection conPubs;
15 SqlCommand cmdSelect;
16
17 conPubs = new SqlConnection( @"Server=localhost;Integrated Security=SSPI;Database=Pubs" );
18
19 cmdSelect = new SqlCommand( "Select * From Titles Order By " + strSortField, conPubs );
20 conPubs.Open();
21 dgrdTitles.DataSource = cmdSelect.ExecuteReader();
22 dgrdTitles.DataBind();
23 conPubs.Close();
24}
25
26void dgrdTitles_SortCommand( object s, DataGridSortCommandEventArgs e ) {
27 BindDataGrid( e.SortExpression );
28}
29
30 </script>
31 </HEAD>
32 <body>
33 <form Runat="Server">
34 <asp:DataGrid ID="dgrdTitles" AllowSorting="True" OnSortCommand="dgrdTitles_SortCommand" CellPadding="10"
35 Runat="Server" />
36 </form>
37 </body>
38</HTML>
因为 dgrdTitles的AllowSorting="True",所有列的页眉都显示为超链列,通过点击超链列引发SortCommand,从而改变不同的绑定。