2

I am new to winforms, what i am trying to do is a simple form:

  • In my form there is a panel.

  • The panel is linked to a user control

  • The user control should fill the panel.

This is my form:

public Form1()
    {
        InitializeComponent();

        UserControl1 userControl = new UserControl1();

        panel1.Controls.Add(userControl);
        userControl.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom)
     | AnchorStyles.Left) | AnchorStyles.Right)));
        userControl.Dock = DockStyle.Fill;
    }

Not working -> the control doest stretch

pic

omriman12
  • 1,644
  • 7
  • 25
  • 48
  • Why you doing this in code level? – huMpty duMpty Mar 03 '14 at 09:55
  • I get the feeling that you meant to set the Dock property of the user control rather than the Panel. What would be the point of setting the Anchor and Dock of the Panel and neither of the user control? – jmcilhinney Mar 03 '14 at 09:59

2 Answers2

7

Try this,

    public Form1()
    {
        InitializeComponent();
        panel1.Dock = DockStyle.Fill;
        UserControl1 userControl = new UserControl1();
        userControl.Dock = DockStyle.Fill;
        panel1.Controls.Add(userControl);

    }

userControl.Dock = DockStyle.Fill; should call before Add to panel1.

You also need to set Anchor property of controls inside UserControl to stretch it based on usercontrol stretch in panel.

Like.

Public Sub UserControl1()

        //This call is required by the designer.
        InitializeComponent();

        //Add any initialization after the InitializeComponent() call.
        Label1.Anchor = AnchorStyles.Top;
        Label2.Anchor = AnchorStyles.Right;
        Label4.Anchor = AnchorStyles.Bottom;
        Label3.Anchor = AnchorStyles.Left;
    End Sub

Note: userControl.Dock = DockStyle.Fill; stretch only usercontrol it self not controls inside user control. To stretch controls of user control you need to set Dock as well as Anchor property accordingly.

Jignesh Thakker
  • 3,638
  • 2
  • 28
  • 35
0

You need to dock your user control as well. Docking panel makes it to dock to the form but not the UserControl.

userControl.Dock = DockStyle.Fill;
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189