gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:52:53 26 4
gpt4 key购买 nike

我有一个希望很简单的问题,但我无法通过 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);
}

关于c# - 从 Winforms 中的不同函数访问控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13671027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com