10

Quick question:

I'm using a Microsoft.VisualBasic.Interaction.InputBox in my C# code to allow users to add websites to a list, but I don't want them to enter an empty string so I give an error popup in case that happens. However, the error will also pop up if the user presses "cancel", which I don't want to happen.

Reading the documentation on it says that pressing "cancel" returns an empty string, hence why it fires the error. Is there a way to still define wether the user pressed "okay" with an empty string or "cancel"?

Thanks in advance,

-Peter

StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Voidpaw
  • 910
  • 1
  • 5
  • 18
  • 3
    Don't think so, the inputbox is quite limited. You should write your own dialog if you need this implemented properly. – stevepkr84 Oct 30 '13 at 11:20

2 Answers2

15

You can't do this. From MSDN

If the user clicks Cancel, a zero-length string is returned.

    Dim result As String = Microsoft.VisualBasic.InputBox("Enter some text")
    If result.Length > 0 Then
        Debug.WriteLine("Something entered and OK Clicked")
    Else
        Debug.WriteLine("Cancel Button Clicked OR Blank String Entered and OK Clicked")
    End If

The easiest solution is just to create your own simple input form and test the DialogResult value

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • Unfortunately they didn't preserve the [original VB behaviour](http://stackoverflow.com/a/20909528/11683) here. – GSerg Nov 05 '14 at 08:13
  • 1
    The DOT.NET wrapper for this initializes the output to "" instead of null. If Okay is pressed the contents of the TextBox is assigned to this.Output (which may be an empty string ""), if Cancel nothing is assigned. Therefore you cannot distinguish between the two outcomes. Some people initialize the default value as " " as a work around. – dmc2005 Dec 30 '15 at 03:06
-4
string a;
            a = Interaction.InputBox("message", "title");
            if (a.Length > 0)
            {
                comboBox2.Items.Add(a);
                // ok
            }
            else
            {
                // cancel
            }