VisualBasic InputBox取消

快速提问:

我在我的C#代码中使用了Microsoft.VisualBasic.Interaction.InputBox ,允许用户将网站添加到列表中,但我不希望它们输入空字符串,所以如果发生这种情况,我会给出一个错误弹出窗口。 但是,如果用户按下“取消”,也会弹出错误,我不想这样做。

阅读上面的文档说按“取消”会返回一个空字符串,因此它会触发错误。 还有一种方法可以定义用户用空字符串或“取消”按下“okay”吗?

提前致谢,

-Peter

你不能这样做。 来自MSDN

如果用户单击“取消”,则返回零长度字符串。

  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 

最简单的解决方案是创建自己的简单输入表单并测试DialogResult

 string a; a = Interaction.InputBox("message", "title"); if (a.Length > 0) { comboBox2.Items.Add(a); // ok } else { // cancel }