Is there a way with the VB interface to either:

GetTextMetrics (ie: take Label, and I want to get the Width of the text that would be outputted by that control.)

Determine if the Text is "larger" than the control.

Basically, I have a form, with multiple "display" labels, that are affected by different colors for the parameters of my application's color coding. HOwever, the text that is displayed in those labes varies based upon the values of a combo box. I populate the combo-box real time, and then when I select Each one in the box, it changes the Text of the Label, and updates the foreground and background colors based upon that current entries settings.

HOwever, sometimes, the text is larger than my initial label size (82x20). Now I can set the AutoSize property, but that does something I don't like: It doesn't obey Form Anchors.

I have 5 labels, each one could change. All the form Anchors are set, so when i resize one label, I can expand the form based upon the width change, and all the other controls follow suit. however, if the other 4 labels are AutoSize=True, they won't resize unless they need to.
WHat I want:

I want an event, (or a precheck function) that tells me the width of a Label when I've Set it's Text propery (or before I set it), which allows me to resize the form to expand the Label dimensions appropriate to fit the text.
Thanks
Jaeden "Sifo Dyas" al'Raec Ruiner

Recommended Answers

All 2 Replies

First you can find the length of the text inside the label control using the len function. And then calculate the width of the label needed.

You can use the following to find the width of the string going into the label control. I used the return values to set the size of the label.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		Dim g As Graphics = Label1.CreateGraphics
		Dim s As SizeF
		s = g.MeasureString("This is a label", Label1.Font)
		Label1.Width = s.Width
		Label1.Height = s.Height
		Label1.Text = "This is a label"
	End Sub

If you want to limit your width then add 50(or whatever) to the measure string.

s = g.MeasureString("This is a label", Label1.Font, 50)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.