C# – AutoSize for Label / TextBox in .NET Compact Framework

ccompact-frameworknet

I'm quite simply going totally bonkers with the omission of the AutoSize-property for the Label and TextBox controls in .NET Compact Framework. I have a simple app, that's supposed to list a bunch of text data (generally between one-liners to a few paragraphs of text) in a TabControl. Everything else works smoothly, but my attempts at dynamically resizing the Label / TextBox -controls I use to display the text are failing miserably.

Here's the way I've tried doing it:

/*
Variables: 
s = The text intended for the TextBox
NewTB = TextBox object
width = Intended width
whiteSpaceAdjustment = amount of pixels per line to adjust "wasted" whitespace due to wrapping
*/

String[] linesArray = s.Replace(Environment.NewLine, "\n").Split(new char[] { '\n' });

int lines = 0;

int lineHeight = g.MeasureString(
        s.Replace("\n", "").Replace("\r", ""),
        LabelFont
    ).ToSize().Height;

foreach (String str in linesArray) {
    if (str.Length == 0) {
        lines++;
        continue;
    }
    szz = g.MeasureString(str, LabelFont).ToSize();
    lines += szz.Width / (width - whiteSpaceAdjustment);
    lines += (szz.Width % width) != 0 ? 1 : 0;
}
NewTB.Height = lines * lineHeight;
NewTB.Width = width;

…but the problem is that the range needed for whiteSpaceAdjustment is too huge. When it's large enough to actually work on the most extreme cases (paragraphs made mostly up of really long words), most boxes end up being a line or two too tall.

I'm probably going to have to implement word wrapping myself, but before I go there, is there anybody with a nice clean solution ready for this?

I'd be forever grateful!

Best Answer

Try this article

www.mobilepractices.com/2007/12/multi-line-graphicsmeasurestring.html

Make sure you also look at the link at the bottom of the article to be able to use different fonts.

If you are using .Net CF 3.5 you may be able to turn their example into an extension method. Otherwise I'd suggest that you create a new control inheriting from the framework control.