So we’ve all had the situation where we’d like to get an input from the user and we’re not too keen on creating a form, adding controls, and writing all the other underlying functionality. Many times, it’s just a lot easier to use an InputBox and validate the data afterward.
Usually everything will go smoothly, that is until you want to accept an empty string as input. The InputBox returns an empty string when the user hits the Cancel button, so how can you tell the difference between Cancel and OK with a blank string?
Well here’s a neat trick. I tested this to work in VB.NET 2005, but I’m sure it’ll work in other versions.
Dim ret As String
Dim dlgRes as DialogResult
ret = InputBox(“Input a value:”, “Input”)
If ret Is String.Empty Then
dlgRes = DialogResult.Cancel
dlgRes = DialogResult.OK
This works because Strings aren’t values, but are instead a reference to a character array in memory. As long as the string is unchanged, only the reference is passed around. InputBox will return [csharp]String.Empty[/csharp] when you click the Cancel button, and you can check if the return value references the same object by using the Is keyword. If it matches, then Cancel was clicked.
Whenever you click OK, the InputBox returns an empty string, but never the empty string, String.Empty. Even if you try passing it [csharp]String.Empty[/csharp] as the initial value, the return value is still a reference to a new, different empty string.
That’s it. Easy as pie!