单击按钮时,动态创建的控件消失 [英] Dynamically created controls disappears when I click button
本文介绍了单击按钮时,动态创建的控件消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表单,通过另一个类,我调用一个方法,以编程方式创建表面板布局,并将其放在表单上。
I have a form and through another class I call a method that programmatically creates a Table Panel Layout, and putting it on the form.
所以我有这个:
Form1.cs
var myNewClass = new MyClass(this);
myNewClass.createDynamicTableLayoutPanel()
private void btnChangeColor_Click(object sender, EventArgs e)
{
var myNewClass = new MyClass(this);
myNewClass.changeColor();
}
MyClass.cs
MyClass.cs
//Method 1 that creates Table Layout Panel with some controls in it
public void createDynamicTableLayoutPanel()
//Method 2 will change the color of controls in Table Layout Panel
public void changeColor()
Button btnChangeColor = new Button();
btnChangeColor.Text = "Change color";
btnChangeColor.Click += (s, e) => {changeColor();}
frm1.TableLayoutPanel1.Controls.Add(btnChangeColor, 0, 2);
推荐答案
您正在创建一个全新的MyClass实例,它没有面板。您需要使用现有实例。
You are creating an entirely new instance of MyClass, which doesn't have the panel. You need to use the existing instance.
// You need to keep using this instance, not create a new one.
var myNewClass = new MyClass(this);
myNewClass.createDynamicTableLayoutPanel()
private void btnChangeColor_Click(object sender, EventArgs e)
{
//var myNewClass = new MyClass(this); // So remove this line.
myNewClass.changeColor();
}
这篇关于单击按钮时,动态创建的控件消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文