如何从公共静态void button_click事件更改System.Windows.Forms.Label的文本



更多详细信息:

假设我正在主函数中创建一个窗体、一个按钮和一个标签,并且我希望在单击按钮时标签文本发生更改。我得到一个错误,标签在范围之外。由于某种原因,我的button_click方法无法到达标签。很明显,我做这件事的方式不对,因为我显然误解了一些东西。但我该如何以正确的方式来做这件事呢?

下面是一个我正在尝试做什么以及我目前如何尝试做的例子。假设我有这个,除了label.Text="新建文本">

using System;
using System.Windows.Forms;
namespace example {
class demo {
public static void Main(String[] args){
Form form = new Form();
Label label = new Label();
label.Text = "Initial Text";
Button button = new Button();
button.Click += button_click;
form.Controls.Add(button);
form.ShowDialog();
}
public static void button_click(object sender, EventArgs e){
label.Text = "New Text";
}
}
}

您发布的代码有两个问题。

  1. 范围
  2. 标签尚未添加到表单中

尝试以下操作:

using System;
using System.Drawing;
using System.Windows.Forms;
namespace example
{
class demo
{
private static Form _form1 = null;
static void Main()
{
//create new instance
_form1 = new Form();
//set value
_form1.Text = "Demo";
//create new instance
Label label1 = new Label();
label1.Location = new Point(10,10);
label1.Name = "label1";

//set value
label1.Text = "Initial Text";
//add to form
_form1.Controls.Add(label1);
//create new instance
Button button1 = new Button();
//subscribe to event(s)
button1.Click += Button1_Click;
//set value
button1.Location = new Point(10, 50);
button1.Name = "button1";
button1.Size = new Size(75, 30);
button1.Text = "Click Me";
//add to form
_form1.Controls.Add(button1);
//show
_form1.ShowDialog();
}
private static void Button1_Click(object sender, EventArgs e)
{
//set value
_form1.Controls["label1"].Text = "New Text";
}
}
}

注意static void Main(string[] args)中的string[] args是不必要的,因为您没有传递任何参数。

为这样的表单编写代码是乏味的,您可以考虑使用Visual Studio社区。

资源

  • 变量

最新更新