Search code examples
c#winformslabelsize

How to determine how many character will fit in a label?


I found this: Is it possible to calculate how many characters will fit in a fixed width label if font is provided in C#?

It didn't work, I have a label and I want to determine how many characters will fit in the label so I can modify the content before assigning, how can I do this, from the above link I tried:

Graphics g = Graphics.FromHwnd(this.lblDestPathContent.Handle);
int intHeight, intWidth;
g.MeasureString(strPath, this.lblDestPathContent.Font
                       , this.lblDestPathContent.Size
                       , null, out intWidth, out intHeight);
this.lblDestPathContent.Text = strPath;

intWidth is returned as the same length as strPath and it will not fit in the label.

The lblDestPathContent is a System.Windows.Forms.Label.

[Edit] An example of the above:

strPath contains 154 characters
the size of the label is returned as {Width = 604, Height = 17}
Font is {Name = "Microsoft Sans Serif", Size=8.25}

After calling MeasureString:

intWidth contains 154
intHeight contains 2

Solution

  • I've managed to do what I need with:

    string strModifiedToFit = strPath;
    bool blnFit = false;
    while(blnFit == false) {
        Size szText = System.Windows.Forms.TextRenderer.MeasureText(strModifiedToFit, 
                                            this.lblDestPathContent.Font);
        if (szText.Width < this.lblDestPathContent.Size.Width) {
            blnFit = true;
        } else {
            strModifiedToFit = strModifiedToFit.Substring(strModifiedToFit.Length - (strModifiedToFit.Length - 1));
        }
    }
    this.lblDestPathContent.Text = strModifiedToFit;
    
    

    The above removes a character from the path until it will fit in the label.