Adjust width of a textbox based on number of characters?

S

Scott Kilbourn

Hi,

I'm writing a control that inherits from TextBox. I need to adjust the
width of this control based on the number of characters in the control. I'm
having a hard time with this.

The problem (as I see it) is that the size of the font is in points, but the
size of the TextBox is in Pixels. I can't figure out a way to use VB.NET to
convert.

Anyone give me a clue?

Thanks
 
S

Scott Kilbourn

Oh yea, forgot to mention... I am using a fixed font. What I need to do is
look at the MaxLength of the TextBox, and adjust the width based on that.

Thanks.
 
K

Ken Tucker [MVP]

Hi,

Dim g As Graphics = TextBox1.CreateGraphics

TextBox1.Width = g.MeasureString(TextBox1.Text, TextBox1.Font).Width + 10

g.Dispose()


Ken
 
S

Scott Kilbourn

This would work, except that I don't actually have a value in the TextBox at
the time. I tried this...

g.MeasureString("XXXXXXXXXXXXXXXXXXXX", TextBox1.Font).Width + 10

And it worked perfectly. :)
 
S

Scott Kilbourn

This works... m_iMaxLineLength is the value for the number of characters
per line.

gTemp.MeasureString(Strings.StrDup(m_iMaxLineLength, "X"),
MyBase.Font).Width + 10
 
S

Scott Kilbourn

Well, it mostly works, anyway. Depending on the max number of characters,
one or two characters are still going to the next line of the multiline
textbox.
 
J

Jason James

Do any of you guys know how to do the
same with printed text? The difference is
that I don't have an object of type

System.Drawing.Printing.PrintPageEventArgs

to use the measurestring method on.

Any ideas?

Thanks,

Jason.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top