在使用其他表单的上下文时,从一个表单访问Label
的值时遇到问题。我可以访问第二种形式的默认标签值,但是当我更改标签值并尝试发送到另一个表单时,我得到标签的默认值而不是新值。
form1中的代码:
public String text1
{
get { return label2.Text; }
set { label2.Text = value; }
}
form2中的代码
private void button3_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
MessageBox.Show("" + frm.text1);
}
答案 0 :(得分:2)
您需要在创建第二个表单时将引用移交给Form1
。类似的东西:
// this is where you open Form2 from Form1
private void button_openForm2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
f2.Show();
}
然后在Form2中你有:
// declare this field in your Form2 class:
Form1 f1;
// this is your constructor in Form2
public Form2(Form1 f1)
{
this.f1 = f1; // some field or property to hold Form1
// possibly other work to do here
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("" + f1.text1);
}
另一种可能性是text1
静态。
答案 1 :(得分:1)
试试这个,
private void button3_Click(object sender, EventArgs e)
{
Form frm = Application.OpenForms["Form1"];
//Here textbox1 is the control name which has the value in Form1
MessageBox.Show("" + frm .Controls["textbox1"].Text);
}