Measuring the 'width' of a string 
Author Message
 Measuring the 'width' of a string

Hi,

I have a textbox and two strings, one longer than the other. If string1 is
too long for the textbox, I want to set it's text property to the shorter
string2. How can I measure the length in pixels of a string?

E.g.

' How do I work out 'string1.width' in the code below?
if textbox.width < string1.width then
    textbox.text = string2
else
    textbox.text = string1
End if

Thanks,

Sam



Sat, 29 Jan 2005 18:18:42 GMT  
 Measuring the 'width' of a string

Quote:

>I have a textbox and two strings, one longer than the other. If string1 is
>too long for the textbox, I want to set it's text property to the shorter
>string2. How can I measure the length in pixels of a string?

You will need to use the Graphics.MeasureString method.  So if you have TextBox1
you could do something like this:

  Dim g As Grapics = TextBox1.CreateGraphics()
  Dim size As SizeF = g.MeasureString(string1, TextBox1.Font)

Then size.Width will have the width in pixels of the string as it would be if
drawn in Textbox1.  Or something like that. :-)

--

*--------={ Fine Art for .NET }=--------*

*---------------------------------------*

       Turn on, tune in, download.



Sat, 29 Jan 2005 18:55:57 GMT  
 Measuring the 'width' of a string

Quote:
> I have a textbox and two strings, one longer than the other. If
> string1 is too long for the textbox, I want to set it's text
> property to the shorter string2. How can I measure the length in
> pixels of a string?

> E.g.

> ' How do I work out 'string1.width' in the code below?
> if textbox.width < string1.width then
>     textbox.text = string2
> else
>     textbox.text = string1
> End if

Call yourtextbox.Creategraphics. The returned graphics object has a
measurestring method.

Armin



Sat, 29 Jan 2005 19:37:32 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. **************!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Help me !!!!!!!!!!!!!!!!!!!!!!!!'''''''''''''''''''''''*************

2. SQL 'strings' passing contents of controls

3. 'Buffer for Return String Too Small'

4. Run-time error '4609': string too long

5. Run-time error '4609': String too long in formfields

6. Looking for 'fuzzy' string comparison routine

7. Showing '&' in string

8. program 'overflow' in string array

9. String types and 'False'??

10. Replacing a password string with '*'

11. Out of string space: 'Split'

12. '&' in a string

 

 
Powered by phpBB® Forum Software