VB.NET Inputbox - How to identify when the Cancel Button is pressed?

前端 未结 12 1626
灰色年华
灰色年华 2021-01-03 22:26

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

相关标签:
12条回答
  • 2021-01-03 23:08

    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
    
    0 讨论(0)
  • 2021-01-03 23:09
    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
    
    0 讨论(0)
  • 2021-01-03 23:11

    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.

    0 讨论(0)
  • 2021-01-03 23:11

    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
    
    0 讨论(0)
  • 2021-01-03 23:13

    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
    
    0 讨论(0)
  • 2021-01-03 23:14
    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 ("").

    0 讨论(0)
提交回复
热议问题