Link to home
Start Free TrialLog in
Avatar of lapucca
lapucca

asked on

How can I make a label control wrap text after I assign the max. size it could have?

Hi, I'm using VS2005, .net 2, C# for windows application.
How can I make a label control wrap text after I assign the max. size it could have?  Thanks.
Avatar of sabeesh
sabeesh
Flag of United States of America image

You acheive this using a CSS class
.word
{
word-wrap: break-word
}


ASKER CERTIFIED SOLUTION
Avatar of Praesidium
Praesidium
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I used the following solution.. but it doesn't offer nice word wrapping I suppose:

Label label = new Label();
label.Text = "this is a veeeeeery long string! Well.. actually it isn't, but it's long enough for this example...";
int charactersFitted, linesFilled;
Graphics g = label.CreateGraphics();
// measure the width of the string.. the size given is the maximum width for the label and a large enough height
g.MeasureString(label.Text, Font, new SizeF(label.Width, 9999), StringFormat.GenericTypographic, out charactersFitted, out linesFilled);
label.Height = Font.Height * linesFilled + 2;

As Praesidium stated, a GrePreferredSize() solution might be a possibility too, but I have no experience and no example of this.
Hmm, yup, GetPreferredSize would also work.

Label label = new Label();
Size maxSize = new Size(100, 100);
label.Text = "this is a veeeeeery long string! Well.. actually it isn't, but it's long enough for this example...";
label.Size = label.GetPreferredSize(maxSize);

This actually a lot less code :P *uses code in project*

Anyway, the GetPreferredSize method calculates the size that it needs to display its text (or whatever is on the label), but it heeds the maximum size you want to give it (it's actually called 'proposedSize', so I'm not sure how aaccurate this actually would be)

Avatar of lapucca
lapucca

ASKER

I turned off the AutosSize and then in designer, I was able to click and drag border of the label box.  That' it.  It does the text wrapping automatically with in the size I made.  thanks.