I have a simple windows application that pops up an input box for users to enter in a date to do searches.
How do I identify if the user clicked on the Cancel butt
I know this is a very old topic, but the correct answer is still not here.
The accepted answer works with a space, but the user can remove this space - so this answer is not reliable. The answer of Georg works, but is needlessly complex.
To test if the user pressed cancel, just use the following code:
Dim Answer As String = InputBox("Question")
If String.ReferenceEquals(Answer, String.Empty) Then
'User pressed cancel
Else if Answer = "" Then
'User pressed ok with an empty string in the box
Else
'User gave an answer
Dim userReply As String
userReply = Microsoft.VisualBasic.InputBox("Message")
If userReply = "" Then
MsgBox("You did not enter anything. Try again")
ElseIf userReply.Length = 0 Then
MsgBox("You did not enter anything")
End If
Here is what I did and it worked perfectly for what I was looking to do:
Dim StatusDate As String
StatusDate = InputBox("What status date do you want to pull?", "Enter Status Date", " ")
If StatusDate = " " Then
MessageBox.Show("You must enter a Status date to continue.")
Exit Sub
ElseIf StatusDate = "" Then
Exit Sub
End If
This key was to set the default value of the input box to be an actual space, so a user pressing just the OK button would return a value of " " while pressing cancel returns ""
From a usability standpoint, the defaulted value in the input box starts highlighted and is cleared when a user types so the experience is no different than if the box had no value.
You can do it in a simpler way using the DialogResult.cancel
method.
Eg:
Dim anInput as String = InputBox("Enter your pin")
If anInput <>"" then
' Do something
Elseif DialogResult.Cancel then
Msgbox("You've canceled")
End if
I like using the IsNullOrEmpty method of the class String like so...
input = InputBox("Text:")
If String.IsNullOrEmpty(input) Then
' Cancelled, or empty
Else
' Normal
End If
input = InputBox("Text:")
If input <> "" Then
' Normal
Else
' Cancelled, or empty
End If
From MSDN:
If the user clicks Cancel, the function returns a zero-length string ("").