Link to home
Start Free TrialLog in
Avatar of YZlat
YZlatFlag for United States of America

asked on

Form does not auto grow if textbox is docked to fill it

I have a windows form with a multiline textbox control on it, the same size as the form. What I want is for textbox to expand downwards as the user types In more text to fill it. To do that I have the following code in TextChanged event:

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

Open in new window


I aslo set Form's property AutoSize to true but the form only grows with the textbox automatically if textbox is not docked to fill the form. And I do need to dock my textbox.

Why isn't my form growing when the textbox is docked and what can I do to fix that?
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
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
Avatar of YZlat

ASKER

(1) and (2) are correct,

form cannot be resized by the user and neither textbox nor form can shrink
Okey dokey...

Try this approach then.
(0) TextBox is simply placed on the Form, WITHOUT Dock.
(1) Compute the required size for the TextBox in your TextChanged() event.
(2) If the required size is larger than the current size then....
(3) Compute the difference between the required size and the current size.
(4) Increase the Height of the TextBox AND the Form by that computed difference.
Avatar of YZlat

ASKER

thanks
Don't you already have it line #9 above?

Just store it in a variable:   * untested code *

    // ... rest of code before this ...
    int requiredHeight = this.textBox1.Font.Height * numLines + padding + border;
    if (requiredHeight > this.textBox1.Height)
    {
        int difference = requiredHeight - this.textBox1.Height;
        this.textBox1.Height = this.textBox1.Height + difference; // increase textbox
        this.Height = this.Height + difference; // increase form
    }