Click to See Complete Forum and Search --> : How can a Form window return a parameter ?


JNic
March 10th, 2008, 09:51 PM
I have my main form, and I would like to add a button that open a form with option. I want the value that are changed to update the one on the main form.

What is the best or a good approach to do this ? (delegate, properties, etc... ?)

If someone can point me to a good article about this or something. Cause I did a search on the website and on the forum and couldn't come up with something.

Thank You

foamy
March 11th, 2008, 02:10 AM
Open the form with what kind of option?

The thread title suggests you should use DialogResult --- that's if you want to know what button the user clicked to close the form... Other than that, please elaborate

cilu
March 11th, 2008, 03:03 AM
If you want to update controls in the main form from the second form, you can pass a reference to the main form to the second, and use it to update the controls.

MikeVallotton
March 11th, 2008, 09:41 AM
If you're doing everything synchronously, then this approach would work well. If you're doing it asynchronously, that's a little more effort.

Make a form (called "form2" in this example). Put at least one button on it, and set the DialogResult of the button to OK. Add a public property to the form, like this:


public partial class Form2 : Form
{
private string aProperty = "";
public string AProperty
{
get { return this.aProperty; }
set { this.aProperty = value; }
}

public Form2()
{
InitializeComponent();
}
}


Modify that public property, adding whatever information you need to pass back to the main form.

On your main form, in the button handler that pops up the second form, put this code:


// create form
Form2 f = new Form2();

// show form
if (DialogResult.OK.Equals(f.ShowDialog()))
{
// get value from form
// do whatever you want with it --> f.AProperty;
}


f.AProperty will contain the information that was put there by "form2".

Does that help?

cjard
March 11th, 2008, 10:04 AM
If you want to update controls in the main form from the second form, you can pass a reference to the main form to the second, and use it to update the controls.

Nooo.. because then that means that the question form depends on the form that asks the question. Youre achieving the OO no no (heh) of high coupling..

You'd either show the question form as a blocking modal dialog of the first form, or you'd expose events on the question form that allow the answering of a question to fire an event that the asking form will pick up on. It all depends how you want control flow to go. The simplest thing to understand is the blocking modal dialog approach

JNic
March 12th, 2008, 10:33 AM
Thank you Mike, work just like I wanted :)

MikeVallotton
March 13th, 2008, 12:38 AM
Cool, glad I could help. :)