Auto resize label width (.NET, mobile)

Hardi
Hardi used Ask the Experts™
on
I'm doing Mobile 5 device application in VS 2005
How do I resize a label to fit the text?
There is no autosize property is there?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
MisbahSr. Software Engineer

Commented:
by the default the label will dynamically resize to hold the text
but in design time if you want to resize it you need to set the AutoSize to false.

Author

Commented:
No it doesn't resize automatically when I set the Text at runtime
That's why I posted this question

Commented:
Use this:

Graphics g = Graphics.FromHwnd(this.Handle);//gets the graphics form the form
SizeF size = g.MeasureString(text1,label1.Font);//gets the size of the text which will be displayed
label1.Size= new Size((int)size.Width, label1.Size.Height);//sets the length of the label (same height)
Learn Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

Author

Commented:
I was trying to use MeasureString before, but FromHwnd wasn't recognised or something.
I'll try it again tomorrow.
Thanks dkloeck
Btw I don't understand the first line, why do we have to pass the form's handle?

Commented:
because FromHwnd needs a handle to a window to get the Graphics object form.
if you would use FromHwnd(this) you would be passing a Form not a handle

Author

Commented:
No, what I asked what why does the Graphic need the form handle only to calculate the width of some text?
Anyway, it's not important =P

Here is the error message:
'System.Drawing.Graphics' does not contain a definition for 'FromHwnd'
Commented:
use this instead, it seems that graphics does not have this function programming for mobile devices:

Graphics g = this.CreateGraphics();//gets the graphics based on the client area
            SizeF size = g.MeasureString(str, label1.Font);//gets the size of the text which will be displayed
            label1.Size = new Size((int)size.Width, label1.Size.Height);//sets the length of the label (same height)

Author

Commented:
Perfect! Thank you dkloeck!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial