1using System; 
 2using System.Collections; 
 3using System.ComponentModel; 
 4using System.Data; 
 5using System.Drawing; 
 6using System.Web; 
 7using System.Web.SessionState; 
 8using System.Web.UI; 
 9using System.Web.UI.WebControls; 
10using System.Web.UI.HtmlControls; 
11using System.Data.SqlClient; 
12
13namespace changedpage 
14
15/// <summary> 
16/// dg_changed_sort 的摘要说明。 
17/// </summary> 

18public class dg_changed_sort : System.Web.UI.Page 
19
20protected System.Web.UI.WebControls.DataGrid myDataGrid; 
21protected System.Web.UI.WebControls.Label SqlStatement; 
22protected SqlConnection myconnection = new SqlConnection(); 
23protected string strsql = "SELECT CompanyName , ContactName , ContactTitle , Phone , Fax FROM Customers "
24DataSet mydataset = new DataSet(); 
25
26private void Page_Load(object sender, System.EventArgs e) 
27
28// 在此处放置用户代码以初始化页面 
29
30if(!IsPostBack) 
31
32binddata(); 
33}
 
34}
 
35private void binddata() 
36
37string strconn = "server = localhost;user id =sa;password =;database =Northwind"
38myconnection.ConnectionString = strconn; 
39strsql = strsql + SqlStatement.Text; 
40
41SqlDataAdapter mycommand = new SqlDataAdapter(strsql,myconnection); 
42mycommand.Fill(mydataset,"customers"); 
43
44myDataGrid.DataSource = mydataset.Tables["customers"].DefaultView; 
45myDataGrid.DataBind(); 
46}
 
47
48Web 窗体设计器生成的代码 
70
71private void myDataGrid_SortCommand(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e) 
72
73                       //这一句很关键,也很值得注意,若" ORDER BY "的两边都要 留空格,否则将会出现错误.  
                                //SqlStatement是一个属性为隐蔵的label
74SqlStatement.Text=" ORDER BY "+e.SortExpression; 
75binddata(); 
76}
 
77
78private void myDataGrid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e) 
79
80myDataGrid.CurrentPageIndex=e.NewPageIndex; 
81binddata(); 
82}
 
83}
 
84}
 
85