C#可以';t动态添加面板

本文关键字:动态 添加 可以 | 更新日期: 2023-09-27 18:20:00

我试图向Form添加一个面板,但它从未出现。但当我改变它的类型时,例如在TextBox上,它会出现。有人知道为什么吗?

HidePanel = new Panel();
HidePanel.ForeColor = Color.Red;
HidePanel.BackColor = Color.Green;//Form.BackColor;
HidePanel.Location = new System.Drawing.Point(531, 181); 
HidePanel.Name = "HidePanel";
HidePanel.Size = new System.Drawing.Size(200, 100); 
HidePanel.Visible = true;
HidePanel.TabIndex = 12;
HidePanel.BringToFront();
Form.Controls.Add(HidePanel);

C#可以';t动态添加面板

您使用了Form,但这不是真的,您应该使用this而不是Form,请尝试此代码。

HidePanel = new Panel();
HidePanel.ForeColor = Color.Red;
HidePanel.BackColor = Color.Green;//Form.BackColor;
HidePanel.Location = new System.Drawing.Point(531, 181); 
HidePanel.Name = "HidePanel";
HidePanel.Size = new System.Drawing.Size(200, 100); 
HidePanel.Visible = true;
HidePanel.TabIndex = 12;
HidePanel.BringToFront();
this.Controls.Add(HidePanel);

更新:

    Form2 frm = new Form2();
    Panel HidePanel = new Panel();
    HidePanel.ForeColor = Color.Red;
    HidePanel.BackColor = Color.Green;//Form.BackColor;
    HidePanel.Location = new System.Drawing.Point(531, 181);
    HidePanel.Name = "HidePanel";
    HidePanel.Size = new System.Drawing.Size(200, 100);
    HidePanel.Visible = true;
    HidePanel.TabIndex = 12;
    HidePanel.BringToFront();
    frm.Controls.Add(HidePanel);
    frm.Show();

我把这段代码放在button1的click事件中,它在form1中声明。