我在方法中动态创建了一个标签“label1”。然后,当我单击一个按钮时,我想删除创建的标签,但如果我写Controls.Remove(label1)它表示该控件在上下文中不存在。我该怎么做才能做到这一点?
编辑:按照 Jon 的建议,我实现了 foreach 循环,但它什么也没做。这是我的代码,我使用的面板是由设计创建的:
void GenerateControls() {
Label labelOne = new Label();
Button btnContinue = new Button();
panel.SuspendLayout();
SuspendLayout();
//btnContinue
btnContinue.BackColor = System.Drawing.Color.Black;
btnContinue.ForeColor = System.Drawing.SystemColors.Menu;
btnContinue.Location = new System.Drawing.Point(145, 272);
btnContinue.Name = "btnContinue";
btnContinue.Size = new System.Drawing.Size(95, 28);
btnContinue.TabIndex = 13;
btnContinue.Text = "Continue";
btnContinue.Visible = true;
Controls.Add(btnContinue);
btnContinue.Click += new System.EventHandler(btnContinue_Click);
//labelOne
labelOne.Location = new Point(0,65);
labelOne.Size = new System.Drawing.Size(100,20);
labelOne.Text = "labelOne";
labelOne.Name = "labelOne";
labelOne.Visible = true;
labelOne.TextChanged += new System.EventHandler(this.lbl_TextChanged);
labelOne.BackColor = System.Drawing.Color.PaleGreen;
Controls.Add(labelOne);
//panel
panel.Controls.Add(labelOne);
panel.Visible = true;
panel.Location = new Point(0,0);
panel.Size = new Size(240, 320);
//
Controls.Add(panel);
panel.ResumeLayout();
ResumeLayout();
}
然后在我点击btnContinue时:
private void btnContinuar_Click(object sender, EventArgs e) {
foreach (Control control in panel.Controls) {
if (control.Name == "labelOne"){
panel.Controls.Remove(control);
break;
}
}
}
我调试它并在 panel.Control 中继续,就好像它是空面板一样。谢谢你的帮助!