Joe
Joe

Reputation: 1214

Resize embedded user controls in a panel C#

Using WinForms in C#, I'm struggling to get an embedded user control to resize correctly. I can add it to the panel with no issue, and the panel resizes as I expect (and want) it to.

To add the UserControl, I'm doing the following:

content.Controls.RemoveAt(0);
content.Controls.Add(c);
content.Controls[0].Dock = DockStyle.Fill;
content.Refresh();

I cannot figure out how to get the newly added control to resize properly, I've also tried using Anchor with Top,Bottom,Left,Right but to no avail. Any help would be appreciated, thanks.

Upvotes: 4

Views: 11276

Answers (3)

Garakk
Garakk

Reputation: 11

I've figured it out.
At the panel which is the base for all added panels add the handler for the Resize event.
At the OnResize() add:

    private void SummaryData_Resize(object sender, EventArgs e)
    {
        foreach (MyPanel pan in this.Controls)
        {
            pan.Dock = DockStyle.Fill;
        }
    }

It worked for me.
I've debugged the code and it seems at the OnResize all my panels lost their Dock setting.

Upvotes: 1

CharithJ
CharithJ

Reputation: 47530

Adding below will resize the user control with the parent control size.

this.Dock = DockStyle.Fill; 

But, if you want to resize the child controls of your user control you will have to set their dock values and anchor values properly. Otherwise, the main user control will resize but the inner child controls of the user control will stay as they are.

You have said;

<< the control moves down, instead of resizing down

If there are some child controls that you want to stretch vertically you might try FlowLayout panel.

Upvotes: 2

Tim Jarvis
Tim Jarvis

Reputation: 18815

Are you 100% sure that Controls[0] is in fact referrencing your control after the add?

Your local var to the control is still valid, you could test that you are setting dock to the right thing by c.Dock = DockStyle.Fill;

Upvotes: 2

Related Questions