Label Width = Text.Width

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,530
Location
Lansing, MI; USA
Programming Experience
10+
I know I can use System.Drawing.Printing.PrintPageEventArgs and the MeasureString() to get the width of the text based on font

I would like to do this in the form's load event, i have 3 labels that i only need the width set based on the text's width (with respect to the font, which can be different depending on the config file the app loads on startup)

how would i go about doing this?

here's what i've tried:
VB.NET:
Private Sub frmMain_Load (...) Handles MyBase.Load
    Dim e As New System.Drawing.Printing.PrintPageEventArgs
    lblEmail1.Width = CInt(e.Graphics.MeasureString(.Email1, lblEmail1.Font).Width)
End Sub
 
VB.NET:
Dim g As Graphics = Label1.CreateGraphics
Label1.Size = Size.Round(g.MeasureString(Label1.Text, Label1.Font))
g.Dispose()
Produces the almost the same result as Label1.AutoSize = True here... (slightly better with heigth :))
 
Last edited:
what's the best way to do this with the width only, no height? i'm gonna look into that code tomarrow too

how about:
VB.NET:
lblEmail1.Width = CInt(g1.MeasureString(.Email1, lblEmail1.Font).Width)
 
Back
Top