-2

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);

        }
    }
Progman
  • 16,827
  • 6
  • 33
  • 48
Nathan
  • 19
  • 1
  • 3
    None of the labels are ever added to...well, anything so they cant appear anywhere. All the panels are going to be on top of each other. Not sure where the docking is supposed to take place. – Ňɏssa Pøngjǣrdenlarp Dec 24 '21 at 20:34
  • *the panel .. doesn't appear* - panels don't, unless you do something that actually makes them visible, like give them a magenta background color – Caius Jard Dec 24 '21 at 21:20
  • If you're new to C#, just use the forms designer. Don't write code to create a UI - it's like pulling your own fingernails out – Caius Jard Dec 24 '21 at 21:21
  • Caius Jard, Thanks, But the issue is, Im not sure how to make a panel for every value in an array in the form designer! – Nathan Dec 26 '21 at 09:56

1 Answers1

0

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
Fredy
  • 532
  • 3
  • 11