In C#, I would like to create a function (method) that has the following behavior:
- When called, create and show a form.
- Wait for the user to enter or select a value on the f开发者_C百科orm.
- Return the selected value.
Is there a concise, readable way to implement this function?
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;
}
Just call Microsoft.VisualBasic.InputBox()
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().
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
}
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.
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;
精彩评论