Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect width of text in vb.net

Tags:

vb.net

Is there a way to detect the actual width of text in a vb.net web app? It needs to be dependant upon its font-style and size.

In vb6 you could copy the text into a label and make it expand to fit then measure its width, but this won't work in vb.net.

like image 798
Urbycoz Avatar asked Mar 09 '11 12:03

Urbycoz


2 Answers

Update: On further inspection, TextRenderer.MeasureText seems a better option:

    Dim text1 As String = "Measure this text"
    Dim arialBold As New Font("Arial", 12.0F)
    Dim textSize As Size = TextRenderer.MeasureText(text1, arialBold)

See Graphics.MeasureString:

Measures the specified string when drawn with the specified Font.

    Dim myFontBold As New Font("Microsoft Sans Serif", 10, FontStyle.Bold)
    Dim StringSize As New SizeF

    StringSize = e.Graphics.MeasureString("How wide is this string?", myFontBold)
like image 55
Mitch Wheat Avatar answered Nov 17 '22 21:11

Mitch Wheat


i have just recently done this in one of my projects here is how i did it

Dim textsize As Size = TextRenderer.MeasureText(cbx_Email.Text, cbx_Email.Font)
        cbx_Email.Width = textsize.Width + 17

this is in a combobox.SelectedIndex changed sub.

The +17 is for the pixels that the dropdown arrow takes up in a combobox so it doesntcover text.

by using control.font it allows the code to dynamically change no matter what font is being used. Using Control.Text means you can use this on anything and wont have to change the code when changing the text of the control or page.

like image 1
Jack Avatar answered Nov 17 '22 20:11

Jack