Monday, 3 September 2012

Telerik rad grid sorting with groupby issue [solved]

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

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

That means if you groupby with a column say “Category” then you’ll loose the default sort that was let say sorted by Name.

So to apply your previous sort with grouped column you just need follow the below steps:

1. Write below 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 prevent mess with original default sort command handle the sortcommand event and write the below snippet

  1. protected void RadGrid1_SortCommand(object source, GridSortCommandEventArgs e)
  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!!!