tags:

views:

314

answers:

4

In a C# form, i have a panel anchored all sides, and inside, a textbox, anchored top/left/right.

When text gets loaded into the textbox, i want it to auto expand itself vertically so that i don't need to scroll the textbox (scroll the panel at most, if there is more text that doesn't fit the panel). is there any way to do this with a textbox? (i'm not constrained to use this control so if there's another control that fits the description, feel free to mention it)

A: 

You can use a Label, and set AutoSize to true.

SLaks
i think autosize is for horizontal. am i wrong?
andrew
A: 

You could anchor it to the bottom, that will ensure that the textbox is resized vertically when ever the form to which it belongs is resized. Also, a textbox that changes its size might not be an elegant thing since it might disrupt the way that other components are displayed. Why don't you give it a maximum size instead of having it resized?

npinti
+1  A: 

I'd suggest using Graphics.MeasureString.

First you create a Graphics object, then call MeasureString on it, passing the string and the textbox's font.

Example

string text = "TestingTesting\nTestingTesting\nTestingTesting\nTestingTesting\n";

// Create the graphics object.
using (Graphics g = textBox.CreateGraphics()) {        
    // Set the control's size to the string's size.
    textBox.Size = g.MeasureString(text, textBox.Font).ToSize(); 
    textBox.Text = text;
}

You could also limit it to the vertical axis by setting only the textBox.Size.Height property and using the MeasureString overload which also accepts int width.

Edit

As SLaks pointed out, another option is using TextRenderer.MeasureString. This way there's no need to create a Graphics object.

textBox.Size = TextRenderer.MeasureString(text, textBox.Font).ToSize(); 

Here you could limit to vertical resizing using Hans' technique, passing an extra Size parameter to MeasureString with int.MaxValue height.

GeReV
You forgot to dispose `g`. You should call `TextRenderer.MeasureString`.
SLaks
+1  A: 

I'll assume this is a multi-line text box and that you'll allow it to grow vertically. This code worked well:

    private void textBox1_TextChanged(object sender, EventArgs e) {
        Size sz = new Size(textBox1.ClientSize.Width, int.MaxValue);
        TextFormatFlags flags = TextFormatFlags.WordBreak;
        int padding = 3;
        int borders = textBox1.Height - textBox1.ClientSize.Height;
        sz = TextRenderer.MeasureText(textBox1.Text, textBox1.Font, sz, flags);
        int h = sz.Height + borders + padding;
        if (textBox1.Top + h > this.ClientSize.Height - 10) {
            h = this.ClientSize.Height - 10 - textBox1.Top;
        }
        textBox1.Height = h;
    }

You ought to do something reasonable when the text box is empty.

Hans Passant
works like a charm
andrew