Wednesday, 23 May 2012

Grouping columns in a Infragistics Grid programmatically

Thanks Infragistics!
Okay, so I have a grid that I want to assign the data source to myself (it will change at run-time).
I would like the user to be able to define the columns that we group by (given the data, it might not be the column you see - for example by Customer means grouping by Customer ID, not Customer Name)
So, exactly how do you get the grid to do the grouping for you?
Well, it isn't as simple as you might think.
Take the following code: This is to bind a simple data set into the grid.

UltraGridBand band = new UltraGridBand("Band 0", -1); UltraGridColumn column1 = new UltraGridColumn("A", -1, null, 0, SortIndicator.Ascending, true); UltraGridColumn column2 = new UltraGridColumn("B", -1, null, 1, SortIndicator.Ascending, true); UltraGridColumn column3 = new UltraGridColumn("C", -1, null, 2, SortIndicator.Ascending, true); UltraGridColumn column4 = new UltraGridColumn("D"); column1.Header.VisiblePosition = 0;

column2.Header.VisiblePosition = 1; 
column3.Header.VisiblePosition = 2; 
column4.Header.VisiblePosition = 3; 
band.Columns.AddRange(new object[] { column1, column2,  column3, column4 }); band.GroupHeadersVisible = false; band.Header.Enabled = false; band.RowLayoutStyle = RowLayoutStyle.GroupLayout; 

You need to serialise the band into the grid with:
 ultraGrid1.DisplayLayout.BandsSerializer.Add(band); 

Set the group by style and put the data source into the grid.
ultraGrid1.DisplayLayout.ViewStyleBand = ViewStyleBand.OutlookGroupBy;
this.ultraGrid1.DisplayLayout.GroupByBox.Hidden = true;
ultraGrid1.DataSource = ds;
(here ds is a simple DataSet that contains 4 columns as you might guess from above)

So, this provides the grouping, yes?
Well, no.
The last parameter to the UltraGridColumn is to define whether it is a grouping column - changing this between true and false makes no odds.

So, what is the magic trick?
Around adding in the band into the BandsSerializer, you need to add
((ISupportInitialize)ultraGrid1).BeginInit();
ultraGrid1.DisplayLayout.BandsSerializer.Add(band); 

((ISupportInitialize)ultraGrid1).EndInit(); 
So blindingly obvious