简体   繁体   中英

Add panels inside a panel dynamically on button click

I'm trying to add panel to already existing panel with name Tablica but im doing it wrong im increasing the global variable each time i add the a panel so the new added panel has different Y location and this makes my panels not overlapping eachother. But now i want to use a different approach so that i dont add them with fixed X,Y location and instead i somehow dock them on top and each new panel addded stays at the top of the parent panel so in other words the last panel added when the button is clicked stays on top of the Tablica panel

This is the code i use now which works except that the last panel is added at the bottom of the panel:

int TabliciLocation = 30; //global variable
private void OK_Click(object sender, EventArgs e)
{
    Panel newPanel = new Panel();
    newPanel.Size = new System.Drawing.Size(1200, 52);
    newPanel.Location = new System.Drawing.Point(16, TabliciLocation);
    Tablica.Controls.Add(newPanel);
    TabliciLocation += 60;
}

So the new approach has to be something like this :

 private void OK_Click(object sender, EventArgs e)
    {
        Panel newPanel = new Panel();
        newPanel.Size = new System.Drawing.Size(1200, 52); 
        newPanel.Dock = DockStyle.Top; // if this can help    
        Tablica.Controls.Add(newPanel);

    }

The FlowLayoutPanel was made for this.

Here is an example; I use different BackColors to show how each new Panel pushes the previous ones down:

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

Random R = new Random();
private void button1_Click(object sender, EventArgs e)
{
    Panel p = new Panel();
    p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
    p.BackColor = Color.FromArgb(123, R.Next(222), R.Next(222));
    p.Size = new Size(flowLayoutPanel1.ClientSize.Width, 50);
    flowLayoutPanel1.Controls.Add(p);
    flowLayoutPanel1.Controls.SetChildIndex(p, 0);  // this moves the new one to the top!
    // this is just for fun:
    p.Paint += (ss, ee) => {ee.Graphics.DrawString(p.Name, Font, Brushes.White, 22, 11);};
    flowLayoutPanel1.Invalidate();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM