Skip to main content
 首页 » 编程设计

c#之从 Winforms 中的不同函数访问控件

2024年02月20日11exmyth

我有一个希望很简单的问题,但我无法通过 google 找到任何解决方案: 我想在运行时添加标签按钮文本框,我可以在我的表单的构造函数中添加,但我无法在构造函数之外访问它们。

像这样:

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

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

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

谢谢

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

在接受 Adil 的回答后,我继续使用以下解决方案,我发现它更好,因为最初注释掉了 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"; 
    } 
} 

请您参考如下方法:

您在构造函数内部声明了标签,使其只能在构造函数中访问,在类作用域的外部构造函数中将标签声明为类成员。

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