To enable sorting and to show a sort order indicator in the column header of a GridView, the following things need to be done:
1. In the .aspx page, define event handlers for "OnSorting" and "OnRowCreated" events. The OnSorting event gets called whenever the grid is sorted by clicking on a column header and OnRowCreated event is called when a row in the grid gets created. Also set the "AllowSorting" attribute to true. The following code snippet shows the attributes of the GridView control:
2. Write the event handlers for OnSorting and OnRowCreated events in the code-behind page.
3. The GridViewSortEventArgs parameter passed to the OnSorting event handler contains the sort direction (ascending or descending) and the sort expression (used to identify the column on which the sorting is done. A particular column in the GridView can be associated with a SortExpression while defining the binding of the column to a particular data field). Store these values in member variables declared within the code-behind page.
4. In the OnRowCreated event, use the SortExpression and SortDirection values stored earlier to determine which image to add and which column to add it to. The following code snippet shows the OnRowCreated event handler:
protected void gridViewInvoiceSearchResult_OnRowCreated(object sender, GridViewRowEventArgs e)
{
// Check whether the row is a header row
if (e.Row.RowType == DataControlRowType.Header)
{
// m_SortExp is the sort expression stored in the OnSorting event handler
if (String.Empty != m_SortExp)
{
// Based on the sort expression, find the index of the sorted column
int column = GetSortColumnIndex(this.gridViewInvoiceSearchResult, m_SortExp);
if (column != -1)
// Add an image to the sorted column header depending on the sort direction
AddSortImage(e.Row, column, m_SortDirection);
}
}
}
// Method to get the index of the sorted column based on SortExpression
private int GetSortColumnIndex(GridView gridView, String sortExpression)
// Method to add the sort icon to the column header
private void AddSortImage(GridViewRow headerRow, int column, SortDirection sortDirection)
No comments:
Post a Comment