10

I have a label with changing text and I wish it to be a single line with fixed length. Whenever the text is longer then the label length, I want it to display whatever fits with "..." at the end. For example:

Some Very Long Text

would look like:

Some Very Lon...

Does anyone know how to do that?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
MichaelB
  • 1,332
  • 1
  • 15
  • 29

2 Answers2

17

One of the options is to set Label.AutoEllipsis to true.

Set AutoEllipsis to true to display text that extends beyond the width of the Label when the user passes over the control with the mouse. If AutoSize is true, the label will grow to fit the text and an ellipsis will not appear.

So, you need to set AutoSize to false. Ellipsis appearance depends on label's fixed width. AFAIK, you need to manually handle text changes to make it depend on text length.

default locale
  • 13,035
  • 13
  • 56
  • 62
  • 3
    Actually a label with autosize set to true WILL show ellipsis if its growth is constrained by its container (ex : a label in a cell of a tableLayoutPanel) – Chris R. Mar 27 '17 at 13:28
  • Note that this solution only works for WinForms – AdvApp Dec 30 '22 at 00:06
6

My solution :

    myLabel.text = Trim(someText, myLabel.Font, myLabel.MaximumSize.Width);

public static string Trim(string text, System.Drawing.Font font, int maxSizeInPixels)
{
    var trimmedText = text;
    var graphics = (new System.Windows.Forms.Label()).CreateGraphics();
    var currentSize = Convert.ToInt32(graphics.MeasureString(trimmedText, font).Width);
    var ratio = Convert.ToDouble(maxSizeInPixels) / currentSize;
    while (ratio < 1.0)
    {
        trimmedText = String.Concat(
           trimmedText.Substring(0, Convert.ToInt32(trimmedText.Length * ratio) - 3), 
           "...");
        currentSize = Convert.ToInt32(graphics.MeasureString(trimmedText, font).Width);
        ratio = Convert.ToDouble(maxSizeInPixels) / currentSize;
    }
    return trimmedText;
}
MichaelB
  • 1,332
  • 1
  • 15
  • 29
  • This method works great for adding an AutoEllipsis type method for my ToolStripLabel which does not have the AutoEllipsis function by default. – Darrel K. May 08 '18 at 09:58
  • 1
    Watch out if you use this... Substring will blow up because of the -3. ratio will converge below 1.0 (and loop forever) depending on the font size and maxSizeInPixels. Graphics are disposable. Make sure the component you use can't auto ellipsis by itself. – Joanis Aug 12 '20 at 16:28