When we talk about Grids in general there are few common features that come to mind, like Filtering , Sorting, Grouping, etc.

In this blog we are going to discuss how we can achieve Grouping and UnGrouping in ComponentOne Spread for WinForms at runtime using code.

In Spread we allow end users to drag Column to GroupBar to create Groups by Column.

SpreadGroup

However, we can achieve the same at runtime using code either on form's load event or on button click or on any function call.

Grouping at Runtime

Spread has different models to work with like DataModel, StyleModel, GroupModel, ViewModel etc. We are going to manually create a GroupDataModel and add groups to it. To add a group we simply create a SortInfo object array and fill it with sorted Columns. SortInfo object contains the sorting information for column in group:


FarPoint.Win.Spread.Model.GroupDataModel gm = new FarPoint.Win.Spread.Model.GroupDataModel(fpSpread1.Sheets[0].Models.Data);
FarPoint.Win.Spread.SortInfo[] si = new FarPoint.Win.Spread.SortInfo[3];
si[0] =new FarPoint.Win.Spread.SortInfo(0, true);
si[1] = new FarPoint.Win.Spread.SortInfo(1, true);
si[2] = new FarPoint.Win.Spread.SortInfo(2, true);
gm.Group(si);
fpSpread1.Sheets[0].Models.Data = gm;


The above code is going to create groups for first three columns.

UnGrouping at Runtime

In order to remove Groups completely and get back to normal SpreadSheet, we will remove the GroupDataModel from SpreadSheet. This is a bit tricky. We would get the TargetModel of current GroupDataModel and assign it to SpreadSheet's data.


fpSpread1.Sheets[0].Models.Data = ((FarPoint.Win.Spread.Model.GroupDataModel)fpSpread1.Sheets[0].Models.Data).TargetModel;


Download sample for detailed implementation: GroupingUnGroupingSpread