Datasheet
❑ AllowSorting: Allows the grid to sort the rows on the basis of column selections. Setting this
to
true enables links on the column headings.
❑
OnSortCommand: Defines the event procedure to call when a column heading is clicked.
Now let's look at the code that uses this grid, starting with the
Page_Load() event:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
// Databind the data grid on the first request only
// (on postback, rebind only in paging and sorting commands)
BindGrid();
}
}
Here we are calling the BindGrid() routine, but only if this is the first time the page has been loaded.
This ensures that the grid, in its initial state, displays data in a default sort order. You'll see how this
works as we go through the code.
Next, we have two events for the grid. The first is for when a page is selected on the grid, and is the
event procedure defined in the
OnPageIndexChanged attribute:
void DataGrid_Page(object sender, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
BindGrid();
}
Notice that the second argument to this procedure is of type DataGridPageChangedEventArgs. This is
automatically sent by ASP.NET and contains two properties, of which we are interested in only
one –
NewPageIndex. This identifies the number of the page selected, so we set the CurrentPageIndex
property of the grid to the selected page number. We then call the BindGrid() routine to re-fetch the
data and bind it to the grid. Later, we'll look at why you need to do this.
The second event procedure is for sorting the grid, and is defined in the
OnSortCommand attribute:
void DataGrid_Sort(object sender, DataGridSortCommandEventArgs e)
{
DataGrid1.CurrentPageIndex = 0;
SortField = e.SortExpression;
BindGrid();
}
The second argument for this procedure is of type DataGridSortCommandEventArgs, which contains
the expression on which the grid is being sorted. In this case, this is automatically set by the
DataGrid
as the column headings are sortable, and so contains the column name.
The first line sets the
CurrentPageIndex of the grid to 0, having the effect of starting the grid at page 1.
We do this because we are re-sorting. We then set
SortField to the sorted field, and rebind the grid.
Notice that
SortField hasn't been declared as a variable – in fact it's a property. This might seem
confusing because properties are always attached to objects, prompting the question what object is this
259
Reading from Databases
57084_08.qxp 30/01/2004 8:03 PM Page 259