So your Form2
must have some value provided by what creates it in order for it to exist. There should never be an instance of Form2 without this information. This tells you that it should be in the constructor of the form (as opposed to the property in this form).
This means that in Form1
you will have something like this:
string someData; //populate based off of user input Form2 childForm = new Form2(someData); //then hide current form and show child form
In Form2, you probably already have a constructor, you just need to change it to something like:
public Form2(string someData)
Next, we need to deal with the child form that returns to the parent form. I believe the preferred way to handle this is to use events. The form has a FormClosing
event, which you can connect to; this will allow your parent form to run some code when the child form is closed.
string someData; // populated based on user input Form2 childForm = new Form2 (someData);
childForm.FormClosing += (sendingForm, args) => { this.Show(); bool result = childForm.DidUserAccept; }
Here, I used the property in the DidUserAccept
child form, as the user accepted or rejected the value. We need to determine what in Form2:
public bool DidUserAccept {get; private set;}
In the button handlers for accepting / canceling, you can set the result accordingly, and then close the form (closing will cause a closed event and run the corresponding code in Form1
.
Servy source share