Autoresize textbox control vertically

The current selected answer does NOT handle lines with no spaces such as "jjjjjjjjjjjjjjjjjjjj"x1000 (think about what would happen if someone pasted a URL)

This code solves that problem:

private void txtBody_TextChanged(object sender, EventArgs e)
{
    // amount of padding to add
    const int padding = 3;
    // get number of lines (first line is 0, so add 1)
    int numLines = this.txtBody.GetLineFromCharIndex(this.txtBody.TextLength) + 1;
    // get border thickness
    int border = this.txtBody.Height - this.txtBody.ClientSize.Height;
    // set height (height of one line * number of lines + spacing)
    this.txtBody.Height = this.txtBody.Font.Height * numLines + padding + border;
}

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, like setting the MinimumSize property.


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.


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