当我处于不同的表单中时,如何从一个表单访问标签中的文本

本文关键字:表单 一个 文本 标签 访问 于不同 | 更新日期: 2024-10-19 00:52:23

在不同表单的上下文中,从一个表单访问Label的值时遇到问题。我可以访问第二个表单中的默认标签值,但当我更改标签值并尝试发送到另一个表单时,我得到的是标签的默认值,而不是新值。

表1:中的代码

public String text1
{            
    get { return label2.Text; }
    set { label2.Text = value; }
}

格式2 中的代码

private void button3_Click(object sender, EventArgs e)
{
    Form1 frm = new Form1();
    MessageBox.Show("" + frm.text1);
}

当我处于不同的表单中时,如何从一个表单访问标签中的文本

在创建第二个表单时,您需要移交对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静态。

试试这个,

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