23

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 button, or merely pressed OK without entering any data as both appear to return the same value?

I have found some examples of handling this in VB 6 but none of them really function in the .NET world.

Ideally I would like to know how to handle the empty OK and the Cancel seperately, but I would be totally ok with just a good way to handle the cancel.

The Sasquatch
  • 763
  • 1
  • 9
  • 17

14 Answers14

26

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.

The Sasquatch
  • 763
  • 1
  • 9
  • 17
12
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 ("").

Kyle Rosendo
  • 25,001
  • 7
  • 80
  • 118
  • This would work, but is there a way to tell the difference between a cancel button push or an empty ok? (Like what Jamie posted below, but in a way that works with .NET) – The Sasquatch May 27 '10 at 21:07
  • The input box is very limited, as Jamie says, just write your own dialog instead. – Hans Olsson May 28 '10 at 07:15
6

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
Theo69
  • 77
  • 1
  • 1
3

1) create a Global function (best in a module so that you only need to declare once)

Imports System.Runtime.InteropServices                 ' required imports
Public intInputBoxCancel as integer                    ' public variable

Public Function StrPtr(ByVal obj As Object) As Integer
    Dim Handle As GCHandle = GCHandle.Alloc(obj, GCHandleType.Pinned)
    Dim intReturn As Integer = Handle.AddrOfPinnedObject.ToInt32
    Handle.Free()
    Return intReturn
End Function

2) in the form load event put this (to make the variable intInputBoxCancel = cancel event)

intInputBoxCancel = StrPtr(String.Empty)    

3) now, you can use anywhere in your form (or project if StrPtr is declared global in module)

dim ans as string = inputbox("prompt")         ' default data up to you
if StrPtr(ans) = intInputBoxCancel then
   ' cancel was clicked
else
   ' ok was clicked (blank input box will still be shown here)
endif
Georg
  • 404
  • 5
  • 7
  • For 64 bit, I had to use `Int64` instead of `Integer`. But it didn't work, treating empty input the same as the cancel button. – user1318499 Nov 15 '20 at 22:42
  • This method no longer works with the newer InputBox in Microsoft.VisualBasic Namespaces. The truly only way to know if Cancel or Ok was selected is to create your own InputBox function. – Georg Nov 17 '20 at 00:39
  • What was the older InputBox? Is that still available in the latest .NET Frameworks somewhere? – user1318499 Nov 18 '20 at 06:43
  • It's part of the Microsoft.VisualBasic NameSpace (in References). Best just to create your own InputBox control if you need the difference. It's easy. – Georg Nov 19 '20 at 22:05
  • The new one that doesn't work is in Microsoft.VisualBasic, isn't it? I'm wondering about the old one that this code did work on. – user1318499 Nov 20 '20 at 08:31
2

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
Rachel Hettinger
  • 7,927
  • 2
  • 21
  • 31
Jgregoire108
  • 109
  • 1
  • 9
0

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
C.Aymar
  • 9
  • 3
0

Base on @Theo69's answer, the following worked for me:

Dim answer As String = Nothing
answer = InputBox("Your answer")
If answer is Nothing Then
    'User clicked the Cancel button.
End If
Jjtx
  • 1
  • 1
0

Base on @Theo69's answer, the following worked for me:

    Dim Answer As String = InputBox("Question", DefaultResponse:=vbCr)
    If Answer = "" Then
        'User pressed cancel
    ElseIf Answer = vbcr Then
        'User pressed ok with an empty string in the box
    Else
        'User gave an answer
        Dim Response As String = Answer.Replace(vbCr, "")
    End If

I used carriage return because I didn't like seeing a character in the textbox.

frigeni
  • 1
  • 2
-1

Guys remember that you can use the try catch end event

Dim Green as integer

Try
    Green = InputBox("Please enter a value for green")
    Catch ex as Exception
        MsgBox("Green must be a valid integer!")
End Try
andrewsi
  • 10,807
  • 132
  • 35
  • 51
Sidney
  • 1
  • Using `Try..Catch` for validation of inputs is generally bad practice. Its almost always better validate your inputs and use `Try..Catch` for the unexpexted – David Wilson Nov 16 '18 at 10:54
  • That doesn't distinguish cancel from empty input. Both throw an exception. – user1318499 Nov 15 '20 at 22:12
-2

Try this. I've tried the solution and it works.

Dim ask = InputBox("")
If ask.Length <> 0 Then
   // your code
Else
   // cancel or X Button 
End If
Tom
  • 26,212
  • 21
  • 100
  • 111
Ahmet Uğur
  • 462
  • 6
  • 12
-2

Although this question is being asked for 5 years ago. I just want to share my answer. Below is how I detect whether someone is clicked cancel and OK button in input box:

Public sName As String

Sub FillName()
    sName = InputBox("Who is your name?")
    ' User is clicked cancel button
    If StrPtr(sName) = False Then
        MsgBox ("Please fill your name!")
        Exit Sub
    End If

   ' User is clicked OK button whether entering any data or without entering any datas
    If sName = "" Then
        ' If sName string is empty 
        MsgBox ("Please fill your name!")
    Else
        ' When sName string is filled
        MsgBox ("Welcome " & sName & " and nice see you!")
    End If
End Sub
zmd94
  • 110
  • 1
  • 8
-3
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
Rachel Hettinger
  • 7,927
  • 2
  • 21
  • 31
-3

Why not check if for nothing?

if not inputbox("bleh") = nothing then
'Code
else
' Error
end if

This is what i typically use, because its a little easier to read.

Michael Parr
  • 134
  • 3
  • 14
-3
Dim input As String

input = InputBox("Enter something:")

If StrPtr(input) = 0 Then
   MsgBox "You pressed cancel!"
Elseif input.Length = 0 Then
   MsgBox "OK pressed but nothing entered."
Else
   MsgBox "OK pressed: value= " & input
End If
Jamie
  • 229
  • 2
  • 3
  • 9