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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With