How to Sort Columns in DataGrid

DataGrids are .NET controls that allow users to display data in a table-like fashion, but with much more functionality and options. DataGrids can support tasks like inserting, editing and deleting data. They can also be paged, which means that you can show smaller amounts of data on your screen at a time and users can flip through them. Sorting in descending order is another feature of DataGrids, however, without custom coding, they cannot be sorted in ascending order. A sortable DataGrid has link buttons for column headers and will update the grid when the user clicks on them.

Other People Are Reading

Enable Default Sorting

Mark the check box for \"Allow sorting\" under the \"Behavior\" section of the \"General\" tab.

4

Click on the \"Columns\" tab in the menu at the left.

5

Make sure that each column is sortable by clicking on its name in the \"Selected Columns\" list and then choosing a value in the \"Sort Expression\" drop-down list.

6

Click the \"OK\" button to save your changes.

Custom Bi-Directional Sorting

1

Perform all the steps for enabling default sorting.

2

Press the F7 key to switch to \"Code Editor\" view.

3

Select your DataGrid from the drop-down list of controls at the top left of the window, and then select the \"Sort Command\" event from the drop-down list of events at the top right. This will create an event handler for you to override the default sorting.

4

Add code to your sort event handler to determine the appropriate sort order and the column to sort by. Copy the code below into your code file.

Tips & Warnings

An alternative to editing your DataGrid in design view to achieve default sorting is to edit it in source view and add the \"Allow Sorting\" property to your DataGrid tag definition and set it to \"True.\"

The DataView object can also be used to filter the contents of your DataGrid with the RowFilter property.

The DataGrid has been replaced by the GridView in versions of .NET after 2.0. The GridView control is very similar but encompasses more functionality.