MichaelB
MichaelB

Reputation: 1362

How do I make a label control truncate long strings with an ellipsis?

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?

Upvotes: 11

Views: 13996

Answers (2)

MichaelB
MichaelB

Reputation: 1362

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;
}

Upvotes: 6

default locale
default locale

Reputation: 13436

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.

Upvotes: 18

Related Questions