asp.net.ph

Skip Navigation Links

Adding Sorting to a DataGrid Control

Controls You Can Use on Web Forms   ASP.NET Data Controls   DataGrid Control


The DataGrid Web server control provides a way for you to add sorting to the grid using these methods:

  • Default sorting   All columns in the grid are sortable. The header for each column contains a LinkButton control ( hyperlink ) that users click to sort by that column.
  • Custom sorting   You define which columns support sorting and what type of button in the column heading users click to sort.

In either case, the grid does not sort the rows. Instead, it notifies you of the sort request by raising an event. You then perform the sort in your own code, usually by passing rebinding to the data source with new sort parameters.

Specifying Default Sorting

To use default sorting, you set properties of the DataGrid control to enable sorting for all columns. You then create an event-handling method to perform the sort.

To specify default sorting

  • [ To be supplied. ]

    The headers for all columns are automatically rendered as LinkButton controls. When the user clicks a column head, the name of the bound field for that column is passed as the sort key.


Specifying Custom Sorting

You can define custom sorting by including bound columns and template columns in the grid.

To specify custom sorting

  1. [ To be supplied. ]

    Columns without a sort expression are not sortable.

If you include template columns, you can specify what type of button users click in the column heading to indicate that they want to sort that column. To include a graphic that users click to sort, use the ImageButton control.

To specify a button type for sorting

  1. [ To be supplied. ]

Performing the Sort

To perform the actual sorting, you write logic to respond to the user’s sort request.

To respond to a sort request

  1. [ To be supplied. ]

    The following example shows how to sort by handling the SortCommand event. The method gets the sort key value and uses it to set the Sort property of a DataView object. The code then rebinds the grid to the DataView object, which automatically returns the data in sorted order.

     [ Visual Basic ] 
    
     [ C# ] 
    
    void myDataGrid_SortCommand ( object src, DataGridSortCommandEventArgs e ) {
       myDataView.Sort = ( string ) e.SortExpression;
       myGrid.DataBind ( );
    }

See Also



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note