2011年9月22日 星期四

Sorting with the DataView

To apply a sort to bound data, you simply set the DataView.Sort property with a string with the corresponding sort information. ADO.NET sorting uses the same syntax as the ORDER BY clause in a SQL query. For example, you might use the following SQL statement to order results by country:
SELECT * FROM Customers ORDER BY Country ASC
The equivalent ADO.NET code is shown here:
ds.Tables["Customers"].DefaultView.Sort = "Country ASC";
dataGrid1.DataSource = ds.Tables["Customers"];
The sort is according to the sort order of the data type of the column. For example, string columns are sorted alphanumerically without regard to case (assuming the DataTable.CaseSensitive property is false). Numeric columns are ordered using a numeric sort. Columns that contain binary data can’t be sorted. Add ASC after a column name for an ascending sort (with smallest values first) or DESC for a descending sort.
Keep in mind that if you want to bind a control to the full DataSet, setting the DataView.Sort property will have no effect because the default DataView isn’t used. Instead, you must modify the DataViewSetting.Sort property exposed through the DataViewManager:
ds.DefaultViewManager.DataViewSettings["Customers"].Sort = "Country ASC";
dataGrid1.DataSource = ds;
DataGrid binding is dynamic and updateable. If you change a value that affects the sort order, the affected row is automatically repositioned. Similarly, if you programmatically modify a DataView while it is in use (or the underlying data), the linked controls update themselves immediately.
You can also use nested sorts. To sort using multiple columns, just add a comma between each sort specification. For example, the following code sorts first country and then orders all rows that have the same country by city:
ds.Tables["Customers"].DefaultView.Sort = "Country ASC, City ASC";
dataGrid1.DataSource = ds.Tables["Customers"];
Alternatively, instead of setting the DataView.Sort property, you can set DataView.ApplyDefaultSort property to true. In this case, ADO.NET automatically creates a sort order in ascending order based on the primary key column the DataTable. ApplyDefaultSort applies only when the Sort property is a reference or an empty string, and when the table has a defined primary key.

程式碼工作室
ERP/EIP/CMS/CHART/REPORT/SPC/EDA/雲端 系統開發整合
ASP/PHP/JSP/ASP.NET 網頁設計
技術指導顧問
信箱:paulwu0114@gmail.com
http://www.coding.com.tw

沒有留言:

張貼留言