views:

422

answers:

3

Hi all

I was wondering if it is possible to have a user control open a winform that allows a user to select options on it and then when he closes the form - the options / values he selected are returned to the user control?

+5  A: 

Why not create some public properies on your dialog form, and access them from the UserControl once the dialog has been closed?

public class OptionsForm : Form
{
    // ...

    public string Option1 { get; set; }
    public bool Option2 { get; set; }
}

And then, within the UserControl:

public void ShowOptionsForm()
{
    using (var form = new OptionsForm())
    {
        if (form.ShowDialog() == DialogResult.OK)
        {
            var option1Value = form.Option1;
            var option2Value = form.Option2;

            // use option values...
        }
    }
}
Steve Greatrex
+1 beat me to the same answer.
Glenn Condron
A: 

here's a short example on how you could do it. It's not complete you'll have to fill in some of the blanks but it should give you an idea of how to solve your problem.

this code goes where you construct your control and you form

MyUserControl ctrl = new MyUserControl();
Action<typeYouPassBack> callBack = myUserControl.FormCallBack;
MyOptionForm form = new MyOptionForm(callBack);

the form class would then have to look something like this: (important part is the action argument)

class MyOptionForm : Form
{
  private readonly Action<typeYouPassBack> _callBack;
  public MyOptionForm(Action<typeYouPassBack> callBack)
  {
    _callBack = callBack;
    Close += form_Close;
  }

  privatre void form_close(object sender, EventARgs e)
  {
     typeYouPassBack postBackData = //populate the postback data
     _callBack(postBackData);
  }
}

the type Action is simply a delegate with the signature void f(T arg). In the above code it's expected for the user control to have amethod called 'FormCallBack' which of course can be named anything you like as long as you use the correct name when assigning it to the 'callback' variable

Rune FS
+1  A: 
BillW