Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoresize textbox control vertically

Tags:

c#

textbox

resize

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)

like image 555
Andrei S Avatar asked May 23 '10 19:05

Andrei S


2 Answers

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;
}
like image 84
David Sherret Avatar answered Oct 22 '22 04:10

David Sherret


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.

like image 20
Hans Passant Avatar answered Oct 22 '22 05:10

Hans Passant