简体   繁体   中英

C# How to return result from Form

I am writing a custom InputBox as I do not want to use the the VB box. So I would like to have the form return the result of the box when closing.

I added an overload to the form's code:

public InputBox()
{
    InitializeComponent();
}

public string InputBox(string LabelText, string Title, string DefaultResult)
{
    return DefaultResult;
}

Is that a good approach or should or can I just modify the constructor? Thanks.

Personally, for these kind of "utility" forms which are typically modal, I prefer to go the static route, having the constructors private. Something like:

private InputBox() // Constructor is private
{
    InitializeComponent();
}

public static string GetValue(string LabelText, string Title, string DefaultResult)
{
    using(var form = new InputBox())
    {
       form.myLabel.Text = labelText;
       form.Text = Title;
       form.myTextBox.Text = DefaultResult;
       if(form.ShowDialog() == DialogResult.OK)
         return form.myTextBox.Text;
    }
    return DefaultResult;
}

And then use it like:

string myValue = InputBox.GetValue("foo","bar","baz");

As requested in the comments, here is some other way to do it, without using static methods... it's basically the same, but you relegate the handling of the form to the caller:

In your InputBox class:

private string _defaultResult;

public InputBox(string LabelText, string Title, string DefaultResult)
{
    InitializeComponent();
    myLabel.Text = LabelText;
    Text = Title;
    _defaultResult = myTextBox.Text = DefaultResult;
}

public string GetValue()
{
    return this.DialogResult == DialogResult.OK ? myTextBox.Text : _defaultResult;
}

And on the caller:

string myValue = "baz";
using(var form = new InputBox("foo", "bar", myValue))
{
   form.ShowDialog();
   myValue = form.GetValue();       
}

Note that I don't encourage this method, since more likely the -only- reasonable way to use this form is a modal dialog, and this could potentially confuse the users of the class.

Having simple static methods (with private constructors so the form can't be instantiated by the caller in any other way) makes more sense for this, as it doesn't force the caller to know how the form is designed to be used: there's just one possible way to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM