Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Stretching a textbox to fit the containing window

I want the text box to stay a certain distance from the top, bottom, left, and right edges of the parent form, and to stretch as the window does.

Currently I have:

private void Form1_SizeChanged(object sender, EventArgs e)
{
    richTextBox1.Size = new System.Drawing.Size(this.ClientSize.Width - 24, richTextBox1.Size.Height);
}

...for the width, but I'm wondering if that's the right way or not. Is there a better way?

like image 698
mowwwalker Avatar asked Dec 18 '11 21:12

mowwwalker


2 Answers

As Moozhe said you need Anchor property of the control

Use the Anchor property to define how a control is automatically resized as its parent control is resized. Anchoring a control to its parent control ensures that the anchored edges remain in the same position relative to the edges of the parent control when the parent control is resized.

But also from my experience do not forget to assign MinimumSize and MaximumSize of the control these properties helps for the control to have certain minimum or maximum size if you resize your form too small or too big.

like image 103
Surjit Samra Avatar answered Sep 21 '22 01:09

Surjit Samra


you can also use Dock property like so:

richTextBox1.Dock = DockStyle.Fill;
like image 10
Ganesh Kamath - 'Code Frenzy' Avatar answered Sep 21 '22 01:09

Ganesh Kamath - 'Code Frenzy'