tags:

views:

144

answers:

6

In C#, I would like to create a function (method) that has the following behavior:

  1. When called, create and show a form.
  2. Wait for the user to enter or select a value on the form.
  3. Return the selected value.

Is there a concise, readable way to implement this function?

A: 

The function should return the type of the input you're looking for and it should do something like...

protected [InputType] ShowInputDialog()
{
    [InputWindowType] w = new [InputWindowType]();
    w.ShowDialog();
    return w.Input;  //Where input is a property that exposes what the user provided as input
}
Eric Mickelsen
As presently written this method doesn't close or dispose of the window. That may (or may not) be a problem.
Michael Todd
@Michael Windows aren't disposable and this one is shown modally.
Eric Mickelsen
Not true. "Because a form displayed as a dialog box is not closed, you must call the Dispose method of the form when the form is no longer needed by your application." From [ShowDialog](http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx)
Michael Todd
+1  A: 

If you are looking for dialog functionality, WPF and WinForms both support this. You simply invoke ShowDialog() on the window / form being shown. This is a blocking call, so until you close the shown dialog, you won't return processing to the calling window.

To return values from this call, simply make properties on your Form / Window, and then inspect those after ShowDialog().

Tejs
This is a nice, general, informative answer. Assuming it works, I am going to approve as soon as the 4 minutes elapses.
mcoolbeth
A: 

Create a form. Add some properties of the values you want to retrieve. THen call from the main form the new form as ShowDialog and when it return, retrieve the values from the properties.

PoweRoy
+1  A: 

Just call Microsoft.VisualBasic.InputBox()

Joel Coehoorn
A: 

Instantiate your form as follows:

Form myForm = new Form();
var result = myForm.ShowDialog();

I don't have a winforms designer to hand, but the return value is an Enum that says clicked ok or cancel and so on.

Once you know that, you can just read the selected value out.

string selectedValue = myForm.SelectedValueProperty;
Russ C
+3  A: 

Create the form you want to show

public partial class SomeForm : Form
{
    public SomeForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DialogResult = DialogResult.OK;
        Close();
    }

    public string SomeValue { get { return textBox1.Text; } }
}

...

private string GetSomeInput()
{
    SomeForm f = new SomeForm();
    if (f.ShowDialog() == DialogResult.OK)
        return f.SomeValue;
    return null;
}
Phil Lamb
You can make this even a little better by nesting the form class inside the same class where you define `GetSomeInput()` (as public static)
Joel Coehoorn
You should use `using` with `ShowDialog` otherwise the form isn't disposed.
Pete Kirkham