Home > Blockchain >  How to programmatically add a Panel in Winforms C#
How to programmatically add a Panel in Winforms C#

Time:10-31

I know this is kind of silly question, but how do I add a Panel to my WinForms project at runtime.

I wanted a Panel to show at startup, but instead, I get nothing (No error messages were found)

Here is the code:

private void Form1_Load(object sender, EventArgs e)
{
 Panel panel = new Panel();
 panel.Size = new Size(200, 100);
 panel.Location = new Point(20,20);
 this.Controls.Add(panel);
 panel.Show();
}

I've tried using panel.Visibility = true; but it's not working :(

CodePudding user response:

Here is a sample for it. A panel alone is a container and not a visible component, you should have something in it. ie:

void Main()
{
    Form f = new Form();
    f.Show();
    MessageBox.Show("Will add panel");
    Panel p = new Panel { Size = new Size(200, 100), Location = new Point(20, 20) };
    f.Controls.Add(p); // nothing would show
    MessageBox.Show("Panel added. Continue to add something in panel");

    Label l = new Label { Left=10, Top=10, Text="A label inside the panel" };
    p.Controls.Add(l);
}
  • Related