paradox
paradox

Reputation: 258

add multiple panels into a form

hi I'm trying to create a list that contains my customised Panel called MyPanel, and add the panels in the list to my from. however it seems like when Form1 load, the form is actually showing 1 panel instead of 10 panels in total. here is my code:

private void Form1_Load(object sender, EventArgs e)
        {
            List<MyPanel> tenPanels = new List<MyPanel>(); 
            for(int i=0;i<10;i++)
            {
                MyPanel mp = new MyPanel();
                tenPanels.Add(mp);
                mp.Name = "digitPanel" + i;
                mp.Location = new System.Drawing.Point(10+i, 32);
                mp.Size = new System.Drawing.Size(147, 173);
                this.Controls.Add(mp);
            }
            foreach(Panel p in tenPanels)
            {
                this.Controls.Add(p);
            }
        }

Form1_Load is visual studio automatically generated event

Upvotes: 3

Views: 2162

Answers (1)

Phil Wright
Phil Wright

Reputation: 22906

You have at least three problems.

1, You are trying to add each new MyPanel twice, once in the main loop and then again in another loop afterwards. I recommend you remove the second loop entirely.

2, The calculated position of each new panel is only 1 pixel to the right of the last one, which means they are going to overlap and hide each other. So update the Point to something sensible.

3, Each time you are adding a new panel the window will perform layout calculations. You could reduce this by asking the control to wait until the last one is added before updating its layout. This will give better performance.

this.BeginUpdate();

// your code

this.EndUpdate();

Upvotes: 2

Related Questions