first, the basic work of realizing this function.
1, first add a GridView, named Gvdata.
2. Set the properties of the control: the following steps
To set properties:
These 4 properties, also set the control allowsorting= "True", 5 points are integral.
3. Write the Gvdata_sorting event for the control
Double-click to write in.
Second, the Code implementation
Double-click to write in.
usingsystem.data;usingsystem.data.sqlclient;namespaceSort { Public Partial classWebForm2:System.Web.UI.Page {protectedVoidpage_load (Objectsender, EventArgs e) { if(!IsPostBack) { //first give it a default state, because the following bin () method requires a status value. viewstate["SortOrder"] ="Depid"; viewstate["Orderdire"] ="ASC"; Bind (); } } //When you click the DataGrid header field, the event is triggered, the value of the corresponding field's DataField is passed, and the viewstate["SortOrder" and the viewstate["Orderdire" property are reset. protectedvoidgvdata_sorting (Objectsender, GridViewSortEventArgs e) {stringspage=e.sortexpression; if(viewstate["SortOrder"]. ToString () = =spage) { if(viewstate["Orderdire"]. ToString () = ="Desc") viewstate["Orderdire"] ="ASC"; Elseviewstate["Orderdire"] ="Desc"; } Else{viewstate["SortOrder"] =e.sortexpression; } bind (); } //get data, sort by custom view, and reorder. PublicVoidbind () {SqlConnection con=NewSqlConnection ("server=.; database=department;uid= ' sa ';p wd= ' 123456 '"); Con. Open (); stringStr="SELECT * from Tdepartment"; SqlCommand cmd=NewSqlCommand (Str,con); Sqldataadaptersqlda=NewSqlDataAdapter (CMD); Datatabletabdata=NewDataTable (); Sqlda.fill (Tabdata); //sorting with custom viewsDataviewview =Tabdata.defaultview; Stringsort= (string) viewstate["SortOrder"] +""+ (string) viewstate["Orderdire"]; View. Sort=sort; Gvdata.datasource=view; Gvdata.databind (); Con. Close (); } }}
third, implementation click on the table header, the implementation of the rearrangement, the effect is as follows:
Iv. Summary
It's hard to get to know the need, and it's not that hard when it comes to knowing the need, and it's really not that hard when it really comes true. Difficult things, always want to escape the difficult heart. Many facts prove: As long as you believe in yourself, calmly face the difficulties, many problems will no longer be a problem. So...
ASP., click on the GridView header to implement the sorting of data