Skip to main content Skip to footer

How to customize characters in a FlexGrid cell

You may want to change the FontStyle, Size or ForeColor of the characters in a single cell. This can be done using the OwnerDrawCell event of the C1Flexgrid which handles the drawing of characters. To begin with, set the DrawMode of C1Flexgrid to OwnerDraw so that the grid triggers OwnerDrawCell event. For the implementation purpose, consider a cell (with row index 1 and column index 1) containing text "John Smith". Following code snippet can be used to set different FontStyle, Size and ForeColor for individual characters of the Cell Text.

private void c1FlexGrid1_OwnerDrawCell(object sender, C1.Win.C1FlexGrid.OwnerDrawCellEventArgs e)  
{  
    //Verify Row/Col index  
    if (e.Col == 1 && e.Row == 1)  
    {  
      //Let the grid draw the BackGround and Border of the cell  
      e.DrawCell(C1.Win.C1FlexGrid.DrawCellFlags.Background | C1.Win.C1FlexGrid.DrawCellFlags.Border);  

      if (!(string.IsNullOrEmpty(e.Text)))  
      {  
        //Create an array of brushes and Fonts  
        SolidBrush[] brushes = new SolidBrush[] {  
                                                    new SolidBrush(Color.Red),  
                                                    new SolidBrush(Color.Green),  
                                                    new SolidBrush(Color.Blue),  
                                                    new SolidBrush(Color.Purple)  
                                                };  
        Font[] fonts = new Font[] {  
                                        new Font("Verdana", 10),  
                                        new Font("Tahoma", 12,FontStyle.Underline),  
                                        new Font("Calibri", 8, FontStyle.Bold),  
                                        new Font("Calibri", 12, FontStyle.Italic)  
                                   };  
        Single x = 0;  
        string text = e.Text;  
        //Traverse celltext and set Font/ForeColor.  
        for (int i = 0; i < text.Length; i++)  
        {  
            string character = text[i].ToString();  
            e.Graphics.DrawString(character, fonts[i % fonts.Length], brushes[i % brushes.Length], e.Bounds.X + x, e.Bounds.Y);  

            //Next character needs to be shifted right;  
            //depending on the space occupied by the previous character as per its FontSize/FontStyle  
            x += (e.Graphics.MeasureString(character, this.c1FlexGrid1.Font)).Width;  
         }  
       }  
       //we're done  
       e.Handled = true;  
    }  
}

If you want render RTF text into grid cells, then you may refer to our product sample called RTFGrid