我有一个简单的问题,我无法通过谷歌搜索任何解决方案:我想在运行时添加标签按钮文本框,我可以在我的表单的构造函数中,但我无法在构造函数之外访问它们。
像这样的东西:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Label changeMe = new Label();
changeMe.AutoSize = true;
changeMe.Left = 50; changeMe.Top = 50;
changeMe.Text = "Change this text from other function";
changeMe.IsAccessible = true;
//changeMe.Name = "changeMe";
this.Controls.Add(changeMe);
}
private void btn_changeLabelText_Click(object sender, EventArgs e)
{
//Would like to achieve this:
//changeMe.Text = "You changed me !! ";
//But I found only this solution:
//Label l; l = (Label)this.Controls.Find("changeMe", true)[0]; l.Text = "You changed Me";
}
}
我注释掉的解决方案是我找到的唯一一个,但我不敢相信没有比这更好的解决方案了。例如,有没有办法让我的控件公开?解决这个问题的好方法是什么?
(每次调用我要设计的对话框时,控件的数量都会有所不同)
谢谢
编辑 - - - - - - - - - - - - -
接受阿迪尔的回答后,我继续使用以下解决方案,我只发现它作为最初评价 this.Control.Find 的方式更好,因为我也想要“n”个文本框,这样我可以轻松地循环它们并读取输入。
public partial class Form1 : Form
{
public struct labels { public Label lbl; public int id; }
List<labels> lbls = new List<labels>();
public Form1()
{
InitializeComponent();
Label changeMe = new Label();
changeMe.AutoSize = true;
changeMe.Left = 50; changeMe.Top = 50;
changeMe.Text = "Change this text from other function";
changeMe.IsAccessible = true;
this.Controls.Add(changeMe);
labels newlabel = new labels();
newlabel.id = 137; newlabel.lbl = changeMe;
lbls.Add(newlabel);
}
private void btn_changeLabelText_Click(object sender, EventArgs e)
{
lbls.Find(i => i.id == 137).lbl.Text = "You changed me";
}
}