Send values from one form to another form

Viewed 406347

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, Form2 should open and Form1 should be in inactive mode (i.e not selectable).

Form2 contains one text box and one submit button. When I type any message in Form2's text box and click the submit button, the Form2 should close and Form1 should highlight with the submitted value.

How can i do it? Can somebody help me to do this with a simple example.

20 Answers

You can use this;

Form1 button1 click

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

And add this to Form2

public string info = "";

Form2 button1 click

private void button1_Click(object sender, EventArgs e)
{

    info = textBox1.Text;
    this.Hide();
    BeginInvoke(new MethodInvoker(() =>
    {
        Gogo();
    }));
}

public void Gogo()
{
    Form1 frm = new Form1();
    frm.Show();
    frm.Text = info;
}

if you change Modifiers Property of a control in a Form to Public, another Forms can access to that control. f.e. :

    Form2 frm;
    private void Form1_Load(object sender, EventArgs e)
    {
        frm = new Form2();
        frm.Show();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(frm.txtUserName.Text); 
        //txtUserName is a TextBox with Modifiers=Public        
    }
// In form 1
public static string Username = Me;

// In form 2's load block
string _UserName = Form1.Username;

the tag Properties receive object value ( C# send value to another form )

private void btn_Send_Click(object sender, EventArgs e)
{
    Form frm = new formToSend();
    frm.tag = obj;
    frm.ShowDialog();
}

Receive value that sent from previous form ( frm )
Ex: sent data is string ( we need to type casting first, because tag value is an object )

public Receive_Form()
{
    InitializeComponent();
    MessageBox.Show((string)this.Tag);
}

How about using a public Event

I would do it like this.

public class Form2
{
   public event Action<string> 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.

Related