Need help docking in c# window forms

300 Views Asked by At

I need help docking in winforms, I googled everywhere and nothing works, somebody please tell me whats wrong, the panel and lable doesn't appear, Please do not judge im new to C#.

        public void doDock()
    {
        string[] test = { "g", "x", "l" };
        foreach(string p in test)
        {
            Panel pnl = new Panel();
            pnl.Dock = DockStyle.Top;
            this.dockpanel.Controls.Add(pnl);
            //
            Label namelabel = new Label();
            namelabel.Location = pnl.Location;
            namelabel.Text = p;
            this.Controls.Add(pnl);

        }
    }
1

There are 1 best solutions below

0
Fredy On

The definition of the panel should be once and outside (before) the loop.

I think you are looking for a FlowLayoutPanel which can support objects to be added one after one, confortably compared to a simple Panel (Location is automatic).

        string[] test = { "g", "x", "l" };
        FlowLayoutPanel pnl = new FlowLayoutPanel();
        pnl.Dock = DockStyle.Fill;
        pnl.FlowDirection = FlowDirection.TopDown;
        this.Controls.Add(pnl);
        foreach (string p in test)
        {
            Label namelabel = new Label();
            namelabel.Text = p;
            pnl.Controls.Add(namelabel);
        }

Then, think to investigate on your object properties - there are many - to let them appear as you wish. Among them:

  • pnl.Dock is the way your panel is docked in the parent object (the Form), so I set to Fill so that there is enough space;
  • pnl.FlowDirection is set to TopDown for the children to be from top to bottom (I figured that was your purpose with DockStyle.Top