mjsnow Posted December 2, 2003 Posted December 2, 2003 I am trying to build a text box in code that is the length of the number of digits I want the textbox to hold. For example, if the textbox is to hold 3 digit numbers, I want it to be only wide enough to hold the three digits. This means I have to calculate the textbox width value based on the font�s size in pixels. So how do I figure out what three digits in a given font is equal to in pixels? Quote
*Experts* mutant Posted December 2, 2003 *Experts* Posted December 2, 2003 You can use the MeasureString method the graphics object. You can create a Graphics object for your form, then call the MeasureString method while passing in the the text you wish to measure and the font of which to return the measurement. You also have to add a little to the Width of the returned size because with the width of the font you might not be able to fit all digits in the textbox because of the TextBox's border. Here is a quick example: 'g will be the graphics object 's will be the size which will be applied to the textbox 'txt will be the name of the textbox 'start by creating the graphics object Dim g As Graphics = Me.CreateGraphics() 'declare a Size object and fill it with the measurement Dim s As Size = g.MeasureString(txt.Text, txt.Font).ToSize 'add some to the width to compensate for the border s.Width += 3 'set the size to the textbox txt.Size = s 'don't forget to dispose of the graphics object g.Dispose() Quote
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.