Tuesday, October 11, 2005

Sorting Directly in a Data Table

One of the nice things about ADO.NET is that it provides a rich set of functionality for sorting without retrieving new data from the database. Furthermore, with ADO.NET, data binding has moved out of the fringe and is now considered the norm – particularly where Web Applications are concerned.



The standard approach to filtering and sorting data in .NET is to use a DataView. In a nutshell, the DataView acts as a layer between your bound object and the underlying data object. For example, to use a DataView to sort the data in a DataGrid, instead of binding the grid directly to a DataSet (just for the sake of argument), you would declare a DataView and set its source to the DataSet. Then you’d configure the sort options on the DataView, and bind the grid to it. Viola! Instant sorting under the hood without the need to write any code!



What if you have a situation where you need to sort data without binding to it? In that case, using the DataView isn’t a viable option. Well, take heart – the DataTable object provides a mechanism that allows you to sort and filter the data directly on the Data Table.



You can use the Select method of a Data Table to sort and filter the data. The syntax is:



    datatable.Select(filterExp, sortExp, rowstatevalue)



The select method returns an array of rows that meet the filter criteria in the sort order specified. Furthermore, you can control what types of rows are returned. You say you only want the rows that have been added since you populated the Data Table? No problem – just set the RowStateValue parameter to DataViewRowState.Added.



What if you want to sort, but not filter the data? That’s not a problem either. You can pass in null to any parameter you don’t want to use. For example:



    DataRow[] sortedRows = customerTable.Select(null, "LastName");

No comments: