从第二个表单获取数据回原始表单

时间:2012-11-01 17:16:14

标签: c# forms variables public

我有两种形式,我使用以下方法创建第二种形式:

Form2 f2 = new Form2();
f2.Show();

Form2有一个公共变量,并且每次鼠标移动都会更改。我在该表单上有一个按钮,按下时会保存变量。现在的问题是我不知道如何将其传递回Form1

1 个答案:

答案 0 :(得分:1)

你应该使用事件。 Form2应该定义一个适当触发的事件(听起来应该是单击按钮时)。然后Form1可以订阅该事件并做任何事情。

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    public event Action<string> MyEvent; //TODO give better name and set arguments for the Action

    private void button1_Click(object sender, EventArgs e)
    {
        string someValue = "Hello World!";  //TODO get value that you want to share

        if (MyEvent != null)
        {
            MyEvent(someValue);
        }
    }
}

然后以你的主要形式:

private void button1_Click(object sender, EventArgs e)
{
    Form2 otherForm = new Form2();

    //subscribe to the event.  You could use a real method here, rather than an anonymous one, but I prefer doing it this way.
    otherForm.MyEvent += value =>
    {
        //do other stuff with "value".
        label1.Text = value;
    };

    otherForm.Show();
}