我怎样才能使这种方法相反

时间:2015-04-23 02:08:48

标签: c#

如何直接将值从表单传递给另一个表单?接收者表格将在屏幕上显示并收听将从主表格发送的传递值。

我知道如何通过委托和事件来做到这一点,但我的不是我想要的。

我需要相反的方式。下面是我可以做的那些代码行。这只能将Form2传递给Form1(主窗体)。我需要这种方法相反。因此,Form1将是发送者Form2将是接收者,并在他们在屏幕上显示时实时传输。

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

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f = new Form2();
        f.IdentityUpdated += new Form2.IdentityUpdateHandler(Form2_ButtonClicked);
        f.Show();
    }

    private void Form2_ButtonClicked(object sender, IdentityUpdateEventArgs e)
    {
        textBox1.Text = e.FirstName;
    }
}

public partial class Form2 : Form
{
    public delegate void IdentityUpdateHandler(object sender, IdentityUpdateEventArgs e);
    public event IdentityUpdateHandler IdentityUpdated;

    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        string sFirstName = txtFirstName.Text;
        IdentityUpdateEventArgs args = new IdentityUpdateEventArgs(sFirstName);
        IdentityUpdated(this, args);
    }
}

public class IdentityUpdateEventArgs : System.EventArgs
{
    private string mFirstName;
    public IdentityUpdateEventArgs(string sFirstName)
    {
        this.mFirstName = sFirstName;
    }

    public string FirstName
    {
        get    { return mFirstName; }
    }
}

1 个答案:

答案 0 :(得分:0)

试试这种方式

public partial class Form1 : Form
{
    public delegate void IdentityUpdateHandler(object sender, EventArgs e);
    public event IdentityUpdateHandler IdentityUpdated;

    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form2 = new Form2();
        form2.Show();
        IdentityUpdated(this, new EventArgs());
    }
}

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
        Form1 form1 = (Form1)Application.OpenForms["Form1"];
        form1.IdentityUpdated += Form1OnIdentityUpdated;
    }

    private void Form1OnIdentityUpdated(object sender, EventArgs eventArgs)
    {
        MessageBox.Show("received");
    }
}