devxlogo

Implementing a two-way sorting for the DataGrid control

Implementing a two-way sorting for the DataGrid control

DataGrid’s sorting functionality is not automatic, the control takes care of “just” rendering the column headers as hyperlinks, and gives you the ability to handle the click on those links, by means of the SortCommand event. Then you manually sort the records (by means of a new DataView from an existing DataSet/DataTable, or by executing a new query with the proper ORDER BY clause). This means that you can customize the way sorting is done, and can implement nice things such as a two-way sorting. Two-way sorting means that when the user first clicks on a column’s header the data is sorted against the specified field in ascending order (by default), and by descending order if the user clicks for a second time the same column. Let’s see how we can add this nice functionality to our Datagrids. The columns are declared with a sort expression as usual:

Then, we handle the SortCommand event. Here we check the sort expression of the previously clicked header, that’s stored as a Datagrid’s attribute. If it is the same of the expression of the just clicked header, it means that the user double-clicked the same header, to invert the sort order. In this case, we add “DESC” to the sort expression. Here’s the code:

Private Sub DataGrid1_SortCommand(ByVal source As Object, _    ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles _    DataGrid1.SortCommand    ' Extract current sort column and order.    Dim currSortExpr As String = DataGrid1.Attributes("SortExpr")    Dim newSortExpr As String = e.SortExpression    ' If the sort expression is the same as the current one,    '  just reverse the direction.    If Not (currSortExpr Is Nothing) AndAlso currSortExpr.ToString = _        e.SortExpression Then        newSortExpr &= " DESC"    End If    ' Remember the new sort expression and rebind.    DataGrid1.Attributes("SortExpr") = newSortExpr    BindDataGrid()End Sub

Finally, in BindDataGrid you retrieve the sort expression from the datagrid’s attributes, and use it to obtain a new DataView with the wanted order, or to execute a new query.

Note: this example assumes that the default sort expression always uses an ascending order, so it adds DESC to invert the order. If you have columns that by default have the DESC option, you should change the code above to parse the sort expression and decide if you have to add DESC, or to remove the existing DESC to have an ascending sorting.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist