How To Dynamically Sort a List<T> During the SortCommand Of a Telerik RadGrid


Have you ever wanted to catch the Sort Event of a Telerik RadGrid, and sort your datasource?   This comes in handy if you are using the rows in the grid as a 1 to 1 map with items in the datasource.  This saves you from needing to worry about working with the rows and columns of a grid, but instead you can work with the List of Objects, and simply ReBin().



protected voidrgdMyGrid_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
    //check the sort order.  if it is descending, then we need to order list that way, otherwise use default of ascending.
    Func<MyObject, string> orderByColumn =null;
    //Figure out which sort column
    switch (e.SortExpression)
        case "FirstName":
            orderByColumn = s => s.FirstName;
        case "LastName":
            orderByColumn = s => s.LastName;
        case "Telephone":
            orderByColumn = s => s.Telephone;
    //now check the sort order, and sort accordingly
    if (e.NewSortOrder == GridSortOrder.Descending)
        myDataSource = myDataSource.OrderByDescending(orderByColumn).ToList();
        myDataSource = myDataSource.OrderBy(orderByColumn).ToList();
    rgdMyGrid.DataSource = null;



MyDataSource is a List<MyObject>.  I was using the datasource for the grid and had to keep them in sync, because sorting the grid did not by default sort the datasource.  You also need to sort the datasource on insert, update, and delete of an item in the RadGrid, if a sort column is selected.

Add comment

  Country flag

  • Comment
  • Preview