Determining max number of characters in a TextBox

G

Guest

Hi,

I have a TextBox that is set to a certain width. From this, I need to
figure out the max number of characters that can fit into the TextBox. I'm
using Courier New font, size 8.25.

I've played around with MeasureText, trying to measure one character (using
Courier New results in each character being the same width) and dividing the
width of the TextBox minus the borders by this value, but it is not working
correctly. It is close, but not quite on. For instance, if my TextBox is
500 wide, my formula tells me that I should be able to fit 75 characters in
the TextBox, but only 72 fit in before it starts scrolling.

I'm obviously missing something, but I'm not sure what. The MeasureText
that I'm using looks like:

txtTest.CreateGraphics.MeasureString("1", txtTest.Font, 10000,
StringFormat.GenericTypographic).Width)

where txtText is using Courier New, 8.25. I've tried it with different
sizes of the font and I get the same results.

Anyone have any ideas that might help me work this out?

Thanks
 
T

Truong Hong Thi

Guess that you did not take textbox's borders and margins into account.
Try something like this:

Dim g As Graphics = txtTest.CreateGraphics
Dim charWidth As Integer = CInt(g.MeasureString("1", txtTest.Font,
10000, StringFormat.GenericTypographic).Width)
g.Dispose()

Dim textBoxWidth As Integer = txtTest.ClientSize.Width -
txtTest.Margin.Horizontal
Dim numberOfChars as Integer = textBoxWidth \ charWidth
 
G

Guest

There is no Margin property in the TextBox control. At least not one that I
can find.
 
C

Claes Bergefall

There is both a Padding and Margins property on Control (and a Padding on
TextBoxBase).

A textbox has margin between the text and the border. In Win32 you use the
EM_GETMARGINS message to get the size of it. Doesn't look like that is what
the Margin or Padding properties use though so you might need to use
P/Invoke for this

/claes
 
T

Truong Hong Thi

It is a new thing of .NET 2.0. If using v1.1, instead of
Margin.Horizontal, try some value like 3.
 

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