Sorting is quite an important built-in feature of DataGrid. It is really easy to implement a sorting functionality in DataGrid. To enable sorting in DataGrid you need to:
- add AllowSorting="True" attribute for DataGrid
- set SortExpression attribute from TemplateColumn element is equal to name of column in theDataTable.
- add code in DataGrid.SortCommand Event handler to customize ascending and descending sorting:
Private Sub ProductsDataGrid_SortCommand(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) _ Handles ProductsDataGrid.SortCommand If Not ProductsDataGrid.Attributes(SortExpressionAttribute) Is Nothing Then
Dim currectSortExpression As String = _ ProductsDataGrid.Attributes(SortExpressionAttribute).ToString()
If currectSortExpression.StartsWith(e.SortExpression.ToString()) Then
If Not currectSortExpression.EndsWith(DescSortOrder) Then ProductsDataGrid.Attributes(SortExpressionAttribute) = _ String.Concat(currectSortExpression, DescSortOrder) Else ProductsDataGrid.Attributes(SortExpressionAttribute) = _ currectSortExpression.Substring(0, _ currectSortExpression.Length - DescSortOrder.Length) End If Else ProductsDataGrid.Attributes(SortExpressionAttribute) = _ e.SortExpression.ToString() End If Else ProductsDataGrid.Attributes(SortExpressionAttribute) = _ e.SortExpression.ToString() End If
SortDataBind() End Sub |
DataGrid Paging
When you display quite large amounts of data, it is not convenient to scroll it. DataGrid proposed a solution for this situation - built-in paging feature.
To enable paging in DataGrid you need to:
- add AllowPaging="True" attribute for DataGrid
- specify PagerStyle-Mode attribute for customizing paging mode.
- Add PagerStyle element like this:
<PagerStyle NextPageText="Next" PrevPageText="Prev" HorizontalAlign="Center"
CssClass="PagingText"></PagerStyle>
- Set PageSize attribute which means number of items to display on a single page of the DataGrid control
- Add code in the DataGrid.PageIndexChanged Event handler:
Private Sub ProductsDataGrid_PageIndexChanged(ByVal source As Object, _ ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) _ Handles ProductsDataGrid.PageIndexChanged ProductsDataGrid.EditItemIndex = -1 ProductsDataGrid.CurrentPageIndex = e.NewPageIndex BindDataGrid() End Sub |
After loading a page, the user is presented a ‘Prev’ and ‘Next’ links at the bottom:
