如何以编程方式在 Winforms C# 中添加面板

How to programmatically add a Panel in Winforms C#

我知道这是个愚蠢的问题,但是如何在运行时将面板添加到我的 WinForms 项目。

我想要 Panel 在启动时显示,但我什么也没得到 (未发现错误消息)

代码如下:

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

我试过使用 panel.Visibility = true; 但它不起作用 :(

这是它的示例。单独的面板是一个容器而不是可见组件,您应该在其中包含一些东西。即:

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