This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!
Sorting Data in a SQL Database
This example accesses a database, binds a DataGrid to it with the column names that are hot. When the column names are clicked, the table will re-sort itself according to the order in that column.
To create a table that can be re-sorted
- Import the necessary namespaces.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQL" %>
Within the <script language="C#" runat="server"> tag, this example implements three functions: Page_Load, MyDataGrid_Sort, and BindGrid. These functions are described in more detail in the steps that follow.
<script language="C#" runat="server">
SQLConnection myConnection;
- Implement a Page_Load function that sets up the connection information for a connection to the "pubs" database. It also checks to see if this page is a PostBack, and if not, calls a custom BindGrid function. For a description of BindGrid, see step 2 of Inserting Data Into a SQL Database.
- Implement the MyDataGrid_Sort function. This function takes the DataGridSortCommandEventArgs E, which is passed in to it from the OnSortCommand attribute in the DataGrid control, and passes it with a call to BindGrid.
protected void MyDataGrid_Sort(Object Src,
DataGridSortCommandEventArgs E)
{
BindGrid(E.SortField);
}
- Implement the BindGrid function. This function is implemented slightly differently from the previous examples. The sortfield parameter (the sort column) is passed to it from the MyDataGrid_Sort function. It uses this information to sort the table according to the specified column.
public void BindGrid(String sortfield)
{
- Set up the SQLDataSetCommand to get the "Authors" table from the "pubs" database (myConnection was set up in step 2).
SQLDataSetCommand myCommand = new SQLDataSetCommand
("select * from Authors", myConnection);
- Set up and fill a new DataSet.
DataSet ds = new DataSet();
myCommand.FillDataSet(ds, "Authors");
- Set up a DataView on the new DataSet, and sort the data using the sortfield.
DataView Source = ds.Tables["Authors"].DefaultView;
Source.Sort = sortfield;
- Bind the DataGrid to the sorted DataView.
MyDataGrid.DataSource=Source;
MyDataGrid.DataBind();
}
To see this example run, go to the ASP+ Quick Start and run sample DataGrid11.aspx.