How to auto ellipsis for compact framework label and textbox controls. RRS feed

  • General discussion

  • I had been trying to achieve that for a while, i finally did. I hope you will find this snippet useful.

    	public static string FitText(string text, Control lbl)
    			// Label and TextBox do not implement CreateGraphics method, so we create an instance of the base Control class
    			Control c = new Control();
    			Graphics g = c.CreateGraphics();
    			float originalStringWidth = g.MeasureString(text, lbl.Font).Width;
    			// the available label with is a bit smaller than it appears because of the paddings and border.
    			float labelWidth = (float)(lbl.Width-10);
    			if (originalStringWidth > labelWidth)
    				// first approximately calculate how many characters can fit into the control
    				int approximateCharLength = (int)((text.Length * labelWidth) / originalStringWidth);
    				// append three dots
    				text = text.Substring(0, approximateCharLength - 3) + "...";
    				// while the resulting text is bigger remove one more character.
    				while (g.MeasureString(text, lbl.Font).Width > labelWidth)
    					text = text.Substring(0, approximateCharLength-- - 3) + "...";
    			return text;
    Thursday, May 27, 2010 8:18 PM

All replies

  • Hi serkan,

    Thank you for your sharing.


    Best regards,
    Guang-Ming Bian - MSFT

    Please remember to mark the replies as answers if they help and unmark them if they provide no help
    Monday, May 31, 2010 7:32 AM