从 WinForms 中的不同函数访问控制



我有一个希望很简单的问题,我无法用谷歌搜索任何解决方案:我想在运行时添加标签按钮文本框,我可以在窗体的构造函数中添加标签按钮文本框,但我无法在构造函数之外访问它们。

像这样:

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

注释掉的解决方案是我找到的唯一解决方案,但我不敢相信没有比这更好的解决方案了。例如,有没有办法公开我的控件?解决这个问题的好方法是什么?

(每次调用我尝试设计的对话框时,控件的数量都会有所不同)

谢谢

编辑--------------------------

在接受阿迪尔的回答后,我坚持了以下解决方案,我只觉得更好,因为最初对此进行了评论。Control.Find way,因为我也想要"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";
    }
}

您在构造函数中声明了标签,使其只能在构造函数中访问,ceclare label作为类成员class scope的外侧构造函数。

Label changeMe = new Label();
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);
}

最新更新