Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Parameters back and forth between forms in C#

I am creating an application where a user will click a button on form1, which will cause form2 to display. The user will then fill out a chat on form2 and then click a button that will close form2 and send back parameters to form1 for processing. How can I do this in C#? I have seen people using properties to do this, but the examples are not clear enough. Can someone give some example code showing me how I can pass the parameters? I would prefer the properties method, but as long as it works, I will count it as the answer.

like image 670
Franz Payer Avatar asked Jan 15 '11 19:01

Franz Payer


1 Answers

Put simply, place your form elements in the second form as you typically would. Then, you can add public accessors to that form that you can then pull from and reference. For instance, if Form2 has a text fields you wanted to pull back, you could:

class Form2
{
  // Form2.designer.cs
  private TextBox TextBox1;

  // Form2.cs
  public String TextBoxValue // retrieving a value from
  {
    get
    {
      return this.TextBox1.Text;
    }
  }

  public Form2(String InitialTextBoxValue) // passing value to
  {
    IntiializeComponent();

    this.TextBox1.Text = InitialTextBoxValue;
  }
}

Then just access it later when you create the form (much like the OpenFileDialog does for Filename etc.

public void Button1_Click(object sender, EventArgs e)
{
  Form2 form2 = new Form2("Bob");      // Start with "Bob"
  form2.ShowDialog();                  // Dialog opens and user enters "John" and closes it
  MessageBox.Show(form2.TextBoxValue); // now the value is "John"
}

Same thing can be done for Int32, Boolean, etc. Just depends on the form's value, if you'd like to cast/validate it, or otherwise.

Alternativly, you can play with the Modifiers property within the form designer where you can make the control public so it's accessible externally. I personally recommend using an accessor so you can validate and confirm the returned results rather than just dumping the value (as this logic is typically found in the form itself, not in every instance you want to call/use Form2)

like image 165
Brad Christie Avatar answered Oct 09 '22 13:10

Brad Christie