Applying New Style on a CellRange in C1Flexgrid with Merged Cells

One of our customers requested for handling the behavior of Text Alignment in C1Flexgrid with Merged Cells. In C1Flexgrid, when applying new styles(text alignment in this case) on a CellRange, the appearance of several cells change. At times, the new style is not honored when the selection contains just the parent merged cell. The problem occurs because the Selection.StyleNew property changes the styles that control the appearance of several cells (not necessarily just the selected ones). Click the image below to observe the default behavior : Therefore, when modifying the styles we need to make sure that the StyleNew property is applied on EACH cell & not on the whole range. CellStyles are normally re-used by many cells. So if you change a style, you are likely to affect many cells. This may or may not be what you want. In this case, the user wanted to change the alignment (and other style elements) of each cell. To do this, one should not apply the same style to many cells. Ideally, each cell should either have its own style or none at all. In this case, one can apply styles to each cell easily. Here is the code to accomplish the same :

private void SetSelectionTextAlignment(TextAlignEnum textAlign)  
    // get selection range  
    CellRange sel = fgBound.Selection;  
    // scan all cells in selection  
    int r, c, sr, sc;  
    for (r = sel.TopRow; r <= sel.BottomRow; r++)  
    for (c = sel.LeftCol; c <= sel.RightCol; c++)  
        // get merged range that this cell belongs to and scan that  
        CellRange rng = fgBound.GetMergedRange(r, c);  
        for (sr = rng.TopRow; sr <= rng.BottomRow; sr++)  
            for (sc = rng.LeftCol; sc <= rng.RightCol; sc++)  
            // get old style, see if alignment should change  
            CellStyle oldStyle = fgBound.GetCellStyle(sr, sc);  
            if (oldStyle == null)  
                oldStyle = fgBound.Styles.Normal;  
            if (oldStyle.TextAlign != textAlign)  
                // create new style for this cell based on old style  
                CellStyle cs = fgBound.Styles.Add(null);  
                // apply new setting, assign to cell  
                cs.TextAlign = textAlign;  
                fgBound.SetCellStyle(sr, sc, cs);  

This is done by scanning the selection, creating a new style for each cell, and applying it. Click the image below to observe the final output : You can refer to the attached samples for complete implementation. Download Sample CS Download Sample VB


GrapeCity Developer Tools
comments powered by Disqus