Create your own custom InputBox

The InputBox method is handy for asking the user to enter a piece of information and was heavily used back in the VB.Old days. So much so, that I see a number of posts on forums that still use this to get data from the user even when using VB.NET. However, one draw back of the InputBox method is that you cannot determine what button was pressed like you can with a MessageBox. So if you want to determine if the user pressed the Cancel button for example, then the only option is to test if a result was returned (i.e. an empty string or not). But this is not foolproof as the user could have pressed the Ok button without entering any data.

So, if you need an InputBox and you also need to know whether the Ok or Cancel button was pressed, then you will need to roll out your own Input Box.

The following snippet demonstrates creating your own custom InputBox replacement by creating a simple form that associates a dialogResult value to the Ok and Cancel buttons allowing you to check what was pressed.

To start, create a new form in your project called InputBoxForm and add the following controls so that it looks similar to the screen shot below:


Control TypeProperties
LabelName: promptLabel
Text: ""
AutoSize: False
TextBoxName: inputTextBox
ButtonName: okButton
DialogResult: Ok
Text: Ok
ButtonName: cancelButton
DialogResult: Cancel
Text: Cancel

Now add the following code to the InputBoxForm:

Note the three properties at the top, this allows us to set the title of the form and the prompt that will be shown in the label that we added. The final property can be read from the calling routine to determine what was entered by the user.

Finally, to use:

Note how the ShowDialog method is used to show the input box. This allows us to test what button was pressed via the DialogResult property. This will be Cancel if the Cancel button was clicked or if the form was closed via the Close box. Otherwise it will be Ok and we can grab the value that the user entered.

Leave a Reply

Your email address will not be published. Required fields are marked *