Detect width of text in vb.net

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.


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)

Tags:

Vb.Net