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:
Now add the following code to the InputBoxForm:
Public Class InputBoxForm
Public Property Title As String
Public Property Prompt As String
Public Property UserInput As String
Public Sub New()
Public Sub New(ByVal title As String, ByVal prompt As String)
Me.Title = title
Me.Prompt = prompt
Private Sub InputBoxForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = Title
promptLabel.Text = Prompt
Private Sub okButton_Click(sender As Object, e As EventArgs) Handles okButton.Click, cancelButton.Click
Me.UserInput = inputTextBox.Text
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:
Dim inputForm As New InputBoxForm("My Input Box", "Please enter a value")
If inputForm.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
MessageBox.Show("You pressed cancel")
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.