ARTICLE

Telerik Rad Grid Sorting With Groupby Issue Solved

Posted by Amit Choudhary Articles | ASP.NET Programming September 04, 2012
Telerik is rad grid is awesome and good to have control when you are in Rapid Application Development environment.
Reader Level:

Telerik's RadGrid is awesome and a good to have control when you are in a Rapid Application Development environment. Built-in features and client-side support is really helpful in solving problems of creating a grid full of features.

Grouping the records is similarly a feature that provides a view to see the records in the manner you see in your Outlook inbox. And with its default properties it works nicely. But what if you have a default sorter applied on your datasource and you use an action to groupby records on the Telerik RadGrid, the groupby command will simply override the data source sorter to its default sorter i.e. the column which is used in the group by.

That means if you groupby with a column say "Category" then you'll loose the default sort that was, let's say, sorted by Name.

So to apply your previous sort with the grouped column you just need to use the following steps:

1. Write the following code in your OnNeedDataSource event of RadGrid:

1.       protected void RadGrid1_OnNeedDataSource(object source,GridNeedDataSourceEventArgs e)
2.
               {
3.
                   // Removing the default sorter from groupby to apply datasource sorting
4.                   if (RadGrid1.MasterTableView.GroupByExpressions.Count > 0)
5.
                   {
6.
                       RadGrid1.MasterTableView.GroupByExpressions[0].GroupByFields[0].SortOrder =
7.
                           GridSortOrder.None;
8.
                   }
9.
               }

2. Now to eliminate the need to mess with the original default sort command, handle the sortcommand event and write the following snippet:

1.       protected void RadGrid1_SortCommand(object source, GridSortCommandEventArgse)
2.
               {
3.
                   var sortField = e.SortExpression;
4.
        
5.
                   // Adding the sorting back if user sorts the grid by grouped field itlself
6.                   if (RadGrid1.MasterTableView.GroupByExpressions.Count > 0)
7.
                   {
8.
                       var groupbySortExpression = RadGrid1.MasterTableView.GroupByExpressions[0].GroupByFields[0].FieldName;
9.
                       if (groupbySortExpression == sortField)
10.
                         RadGrid1.MasterTableView.GroupByExpressions[0].GroupByFields[0].SortOrder = e.NewSortOrder;
11.
                 }
12.
             }


Now you have both features applied, RadGrid Grouping and your default sorter in the grouped records.

Note :- This approach will not work if you have multicolumn support enabled.

Cheers!!!
 

COMMENT USING

Trending up