compare string lenth to text box drawing area

  • Thread starter Thread starter Dennis C. Drumm
  • Start date Start date
D

Dennis C. Drumm

How can I determine if a string will fit in the display area of a text box?

I don't want to use a char count because the width of each char can vary. I
suspect I need to convert the string to a graphic using the text box's font,
but I'm not sure how that would be done.

Thanks,

Dennis
 
Dennis,

You could always take the text that you want to place in the textbox and
pass it to the MeasureString method on the Graphics class. You would get
the Graphics instance for the textbox by calling the static FromHwnd method
on the Graphics class, passing the handle from the TextBox. Then, you would
pass the text and the font. The only thing you would have to do is handle
the border, but in the case of the TextBox, you might be able to use the
ClientRectangle property to get that information.

Hope this helps.
 
Here is some code that will find out if a string fits in a label, and if
doesn't, display it in a dynamically placed label that's wider, and covers
the regular display area (the idea being this would pop up when the mouse
hovered over the original label, and go away when the mouse left the area.)

System.Drawing.SizeF stringSize = new SizeF();
stringSize = e.Graphics.MeasureString(lbl.Text, lbl.Font);
if ( stringSize.Width > lbl.Width )
{
MoreText.Text = lbl.Text;
// The following line assumes MoreText has the same parent as lbl
MoreText.Location = new Point( lbl.Location.X, lbl.Location.Y);
int Over = ( this.Width - (MoreText.Left + MoreText.Width + 2) );
if ( Over < 0 )
{
// if longer label doesn't fit on form,
// then start it further to the left (adding negative number)
lblMoreText.Left += Over;
}

MoreText.BringToFront();
MoreText.Visible = true;

}
 
Back
Top