Skip to main content Skip to footer

How to sort a selected cell range in C1FlexGrid

There are occasions when users need to implement sort on a selected range of cells and not the entire C1Flexgrid. There's no direct method to implement this and here we will discuss implementation of the very same subject. Say there is a C1Flexgrid on the Form with a particular CellRange selected using Mouse or code and we need to sort that cell range. Lets drop a button on the Form besides the C1Flexgrid and start writing some code in the Click event of the button. And here's the logic:

C1.Win.C1FlexGrid.CellRange cr = this.c1FlexGrid1.Selection;
// create a temporary C1FlexGrid object
var fg = new C1.Win.C1FlexGrid.C1FlexGrid();
// add the same number of rows and columns to the temp flexgrid as the cell range
fg.Cols.Count = cr.c2 - cr.c1 + 1;  
fg.Cols.Fixed = 0;  
fg.Rows.Count = cr.r2 - cr.r1 + 1;  
fg.Rows.Fixed = 0;
// populate the temp flexgrid with data from the cell range
for (int i = cr.r1; i <= cr.r2; i++)  
{  
for (int j = cr.c1; j <= cr.c2; j++)  
{  
    fg[\_row, \_col] = this.c1FlexGrid1[ i ,  j ];  
    _col += 1;  
}  
_row += 1;  
_col = 0;  
}
// sort temporary flexgrid
fg.Sort(C1.Win.C1FlexGrid.SortFlags.Ascending, 0);
// populate the sorted data from temp grid into original grid
for (int i = cr.r1; i <= cr.r2; i++)  
{  
for (int j = cr.c1; j <= cr.c2; j++)  
{  
    this.c1FlexGrid1[ i ,  j ] = fg[\_row, \_col];  
    _col += 1;  
}  
_row += 1;  
_col = 0;  
}