Skip to main content Skip to footer

How to clip long text with ellipses

The partial view of the text, may give the user an impression of the wrong cell value. This blog explains how you can change the appearance of the cells with long text values, so as to make the users understand that the cell value is longer than what is displayed. The approach in this blog changes the long values to display dots at the end of the cell text(Cell value 12345.678910 is displayed as 12345.67...). It does not change the actual cell value, only the display value has been changed. When you enter edit mode, the complete value of the cell is displayed.

TrueDBGrid Clipped Text

We can accomplish this by drawing the cells manually. We'll use the OwnerDrawCell event to draw the cell contents. All we did is compare the length of the text in the cell with the cell width. If the length of the cell text is longer we keep on dividing the string that represents the cell value to substrings, until the cell width is longer than the cell text. At the end, we simply append the dots to display the desired results in the cell.

void c1TrueDBGrid1_OwnerDrawCell(object sender, C1.Win.C1TrueDBGrid.OwnerDrawCellEventArgs e)  
{  
  e.Handled = true;  
  e.Graphics.FillRectangle(new SolidBrush(e.Style.BackColor), e.CellRect);  
  object val = c1TrueDBGrid1.Columns[e.Col].CellValue(e.Row);  
  SizeF size = e.Graphics.MeasureString(val.ToString(), c1TrueDBGrid1.Splits[0].DisplayColumns[e.Col].Style.Font);  
  int width = (int)Math.Ceiling(size.Width);  
  int cellwidth = e.CellRect.Width;  
  if (width > cellwidth)  
  {  
    int r = 1;  
    string s = e.Text;  
    string ns = "";  
    while (width > cellwidth - 5)  
    {  
      ns = s.Substring(0, s.Length - r);  
      size = e.Graphics.MeasureString(ns.ToString(), c1TrueDBGrid1.Splits[0].DisplayColumns[e.Col].Style.Font);  
      width = (int)Math.Ceiling(size.Width);  
      r++;  
      s = ns;  
    }  
    ns = ns + "....";  
    e.Graphics.DrawString(ns, e.Style.Font, new SolidBrush(Color.Black), new PointF(e.CellRect.X, e.CellRect.Y));  
   }  
   else  
   {  
     e.Graphics.DrawString(e.Text, e.Style.Font, new SolidBrush(Color.Black), new PointF(e.CellRect.X, e.CellRect.Y));  
   }  
}