我设计中的文本标签文本不会更改
问题描述:
我在Form1
里面有一个文本标签,名称为txtOn
。我已将其修饰符设置为public
。现在,我尝试通过单击按钮使用以下代码更改文本。没有任何反应,但点击了按钮!记录到以进行调试。我设计中的文本标签文本不会更改
如何使文本标签的文本更改成功?
private void button1_Click(object sender, EventArgs e)
{
Form1 home = new Form1();
home.txtOn.Text = "test!";
System.Diagnostics.Debug.WriteLine("button clicked!");
}
答
那是因为你还没有加载Form1的新实例。
Form1 home = new Form1();
home.show();
home.txton.text="test!";
如果你想改变它的形式的当前实例,您将需要使用此关键字:
this.txton.text="test!";
答
NO,变化,在你的窗体加载标签文本或初始化像
private void button1_Click(object sender, EventArgs e)
{
Form1 home = new Form1();
home.Show();
System.Diagnostics.Debug.WriteLine("button clicked!");
}
Public Form1()
{
txtOn.Text = "test!";
}
方法假设你试图完全打开不同的形式。如果它是相同的形式,那么你根本不需要创建一个单独的表单实例。你只能说txtOn.Text = "test!";
答
你可能想要么
// Start NEW Form1, show it and change the button
private void button1_Click(object sender, EventArgs e)
{
Form1 home = new Form1();
home.txtOn.Text = "test!";
home.Show(); // <- do not forget to show the form
System.Diagnostics.Debug.WriteLine("button clicked!");
}
或
// On the EXISTING Form1 instance change the button
// providing that "button1_Click" method belongs to "Form1" class
private void button1_Click(object sender, EventArgs e)
{
txtOn.Text = "test!";
System.Diagnostics.Debug.WriteLine("button clicked!");
}
答
不工作,因为你是重新实例化Form1中时,它已经可用。您还没有更改按钮上的文字在同一个实例作为一个在UI
尝试
private void button1_Click(object sender, EventArgs e)
{
txtOn.Text = "test!";
}
。
答
您只能创建一次Form1。 样品
`Form1 home = new Form1();
home.button1.Click += new System.EventHandler(this.button1_Click);
private void button1_Click(object sender, EventArgs e)
{
home.txtOn.Text = "test!";
System.Diagnostics.Debug.WriteLine("button clicked!");
}`
答
您需要公开您的标签或财产。
在形式上2
public string LabelText
{
get
{
return this.txtOn.Text;
}
set
{
this.txtOn.Text = value;
}
}
然后,你可以这样做:
form2 frm2 = new form2();
frm2.LabelText = "test";
答
你又创建相同形式的又一个对象。所以标签没有改变。试试下面的代码。
private void button1_Click(object sender, EventArgs e)
{
txtOn.Text = "test!";
System.Diagnostics.Debug.WriteLine("button clicked!");
}
为什么要初始化Form Form Form1(); Form1();'?你应该使用已经定义的变量'txtOn'。 – Michael
你为什么在你的按钮单击中实例化一个Form1的新实例?只需执行'this.txtOn.Text =“test1”;'。 – Tim