Jan Schreuder on .Net

.Net code samples, experiences, observations

View my professional profile on LinkedIn

Recent Posts

Tags

News

  • Inappropriate comments will be deleted at my discretion.

    The information and code samples in this weblog is provided "AS IS" without warranty of any kind, either expressed or implied, including but not limited to the merchantability and/or fitness for a particular purpose.

Community

Email Notifications

Tool suppliers

Tools

General

Microsoft

Favorite blogs

Archives

How to: Make a text fit your labels

I've had this problem before, and I just ran into it again: The text I'm trying to add to a label is too long and now the text spans more than one line and it doesn't fit anymore...

In my situations, I could very well live with having this text truncated to something that would fit. I can add the entire text to a tooltip, so that it will show when the user hovers the label. I created some code to do this in a generic way. First, I had to figure out how wide the text was. That can be done using the MeasureString method from the Graphics method:

private static int PixelLength(string text, Font thisFont)
{
    Label    lbl = new Label();           // Create a new label
    Graphics g = lbl.CreateGraphics();    // Create the graphics for this label
    if (thisFont == null)
    {
        thisFont = lbl.Font;
    }
    return (int)g.MeasureString(text, thisFont).Width;
}

Using this method, I can calculate the width in pixels for any string I want using any font. Now that we know what the length of a text in pixels for the specified font will be, we can create the method to truncate the text:

public static string FitText(string text, int pixels, Font thisFont, string addAfter)
{
    Label    lbl = new Label();         // Create a new label 
    Graphics g = lbl.CreateGraphics();  // Create the graphics for this label
    SizeF    w;                         // Size object to be used for calculating
    float    available = pixels - 1;    // Adjust the available pixels to handle whitespace
    bool     isTruncated = false;       // Assume the string will fit
    string   result  = string.Empty;    // Will contain the result for this method
 
    // When there is no font specified, assign the label font as the font to be used
    if (thisFont == null) thisFont = lbl.Font;
    // When an AddAfter text was specified, calculate the length of
    // that text and adjust the available white space
    if (addAfter.Trim().Length > 0) available -= g.MeasureString(addAfter.Trim(), thisFont).Width;
    // If there is room to fit the string
    if (available > 0)
    {
        // Now assign the text to the result
        result = text;
        do
        {
            // Calculate the width of the Result string using the specified font
            w = g.MeasureString(result, thisFont);
            // If there aren't enough pixels available, truncate the string
            if (w.Width > available)
            {
                result = result.Substring(0, (int)((result.Length * available) / w.Width));
                isTruncated = true;
            }
        } while (w.Width > available);
        // If the string was truncated, we need to add the AddAfter string if
        // there was one specified
        if (isTruncated && (addAfter.Trim().Length > 0))
        {
            result += addAfter.Trim();
        }
    }
    return result;
}

The method above takes the text as the first argument. The second argument is the width from the label we need to fit the text into. The third argument would supply the font used to display the text. The last argument allows you to specify text that would follow the original text if the method would truncate the original text, for example "...". So now that this method is done, I can add the text to my label in the following way:

label2.Text = FitText("This is a very long text which will not fit the label in this situation",
label2.Width, label2.Font, "...");

The label would then display something like the following, which I think is a lot better.

Comments

jacques said:

its not working. please try again.

copying and pasting that into the compact framework code produces a not support exception

# September 29, 2009 4:33 PM

Jan Schreuder said:

Very likely, since the code was not written for the compact framework :-)

# September 29, 2009 8:41 PM

oldovets said:

Standard Label class has a property named AutoEllipsis which do the same

# January 19, 2010 1:55 PM

Jan Schreuder said:

I know, but it was an old version of ASP.Net for which we did this.

# January 19, 2010 4:27 PM

GR said:

Thanks for the code Jan! Also, it will work for Compact Framework if you create the graphics from the form instead of the label.

# April 22, 2010 5:39 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Please add 1 and 7 and type the answer here: