Adding a DockStyle.Fill control at run-time

This one was simple to resolve but it did halt my progress for about 5-6 minutes recently. I had a form (actually a user control) that had a control on it added at design time docked to the right. During run time I was adding a new WinForms control that I had set to DockStyle.Fill. Imagine my surprise when the dynamically added control filled the entire user control instead of adhering to the expected docking behavior. Turns out the control that fills the rest of the space always needs to be the first control that’s on the form or user control. When doing it dynamically, you need to call ControlCollection.SetChildIndex. Here’s a sample code snippet :

private void MainForm_Load(object sender, EventArgs e)
    TextBox textBox = new TextBox() { Multiline = true, Dock = DockStyle.Fill };
    this.Controls.SetChildIndex(textBox, 0); // move it to the 0th position

2 thoughts on “Adding a DockStyle.Fill control at run-time

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s