Send values from one form to another form

后端 未结 19 2494
眼角桃花
眼角桃花 2020-11-21 11:45

I want to pass values between two Forms (c#). How can I do it?

I have two forms: Form1 and Form2.

Form1 contains one button. When I click on that button, Fo

19条回答
  •  灰色年华
    2020-11-21 12:05

    How about using a public Event

    I would do it like this.

    public class Form2
    {
       public event Action SomethingCompleted;
    
       private void Submit_Click(object sender, EventArgs e)
       {
           SomethingCompleted?.Invoke(txtData.Text);
           this.Close();
       }
    }
    

    and call it from Form1 like this.

    private void btnOpenForm2_Click(object sender, EventArgs e)
    {
        using (var frm = new Form2())
        {
            frm.SomethingCompleted += text => {
                this.txtData.Text = text;
            };
    
            frm.ShowDialog();
        }
    }
    

    Then, Form1 could get a text from Form2 when Form2 is closed

    Thank you.

提交回复
热议问题