Sorting with a DataView

The next example uses a page with three GridView controls. When the page loads, it binds the same
DataTable to each of the grids. However, it uses three different views, each of which sorts the results
using a different field.

The code begins by retrieving the list of employees into a DataSet:

// Create the Connection, DataAdapter, and DataSet.
string connectionString =
WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
SqlConnection con = new SqlConnection(connectionString);
string sql =
"SELECT TOP 5 EmployeeID, TitleOfCourtesy, LastName, FirstName FROM Employees";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
// Fill the DataSet.
da.Fill(ds, "Employees");

The next step is to fill the GridView controls through data binding. To bind the first grid, you
can simply use the DataTable directly, which uses the default DataView and displays all the data.
For the other two grids, you must create a new DataView object. You can then set its Sort property explicitly.

// Bind the original data to #1.
grid1.DataSource = ds.Tables["Employees"];
// Sort by last name and bind it to #2.
DataView view2 = new DataView(ds.Tables["Employees"]);
view2.Sort = "LastName";
grid2.DataSource = view2;


// Sort by first name and bind it to #3.
DataView view3 = new DataView(ds.Tables["Employees"]);
view3.Sort = "FirstName";
grid3.DataSource = view3;
Sorting a grid is simply a matter of setting the DataView.Sort property to a valid sorting expression.
This example sorts by each view using a single field, but you could also sort by multiple fields,
by specifying a comma-separated list. Here’s an example:
view2.Sort = "LastName, FirstName";

■Note The sort is according to the data type of the column. Numeric and date columns are ordered from
smallest to largest. String columns are sorted alphanumerically without regard to case, assuming the
DataTable.CaseSensitive property is false (the default). Columns that contain binary data cannot be sorted.
You can also use the ASC and DESC attributes to sort in ascending or descending order.

Once you’ve bound the grids, you still need to trigger the data binding process that copies the
values from the DataTable into the control. You can do this for each control separately or for the
entire page by calling Page.DataBind(), as in this example:

Page.DataBind();

: