The output of above example is shown below: -

In the above example, it can be seen that the style objects modify every item displayed by a DataGrid. You can also apply objects to individual columns in a DataGrid by using different style of objects with different columns.
When this DataGrid is displayed, all the columns are displayed with a specific style.
Sorting Columns in a DataGrid Control
The DataGrid control has built-in support for sorting columns. Sorting can be done for all the columns in a DataGrid or for only particular columns.
To enable sorting for all the columns in a DataGrid, the AllowSorting property is set to True and a subroutine is associated with the SortCommand event. The following example demonstrates it: -
| Example 48 ExpertDataGridSort.aspx:- |
<%@ Import Namespace="System.Data.SqlClient" %>
<Script Runat="Server">
Sub Page_Load
If Not IsPostBack Then
BindDataGrid( "ProductName" )
End If
End Sub
Sub BindDataGrid( strSortField As String )
Dim conNorthwind As SqlConnection
Dim cmdSelect As SqlCommand
conNorthwind = New SqlConnection( "Server=localhost;UID=sa;PWD=secret;Database=Northwind" )
cmdSelect = New SqlCommand( "Select * From Products Order By " & strSortField, conNorthwind )
conNorthwind.Open()
dgrdProducts.DataSource = cmdSelect.ExecuteReader()
dgrdProducts.DataBind()
conNorthwind.Close()
End Sub
Sub dgrdProducts_SortCommand( s As Object, e As DataGridSortCommandEventArgs )
BindDataGrid( e.SortExpression )
End Sub
</Script>
<html>
<head><title>ExpertDataGridSort.aspx</title></head>
<body>
<form Runat="Server">
<asp:DataGrid
ID="dgrdProducts"
AllowSorting="True"
OnSortCommand="dgrdProducts_SortCommand"
CellPadding="9"
Runat="Server" />
</form>
</body>
</html> |
| |
The output of above example is shown below: -

In the above example, the header text for all the columns appears as hypertext links because the AllowSorting property is enabled for the DataGrid . When a link is clicked, the SortCommand event is raised. This event is associated with the dgrdTitles_SortCommand subroutine by the DataGrid control's OnSortCommand property.
The dgrdTitles_SortCommand subroutine retrieves the name of the column selected for sorting and passes it to the BindDataGrid subroutine. The actual sorting is performed in the BindDataGrid subroutine. The records are sorted with the help of a SQL Order-By clause.
|