检查VB.NET是否为空

检查VB.NET是否为空,vb.net,textbox,null,Vb.net,Textbox,Null,无法找出为什么不选中文本框以及所选颜色如果我没有输入颜色,它会标记“请输入字段”消息,但是如果我选择了颜色,但没有在“名称”文本框中输入任何内容,则它会继续并在msgbox中输出一个空白字符串 代码是: Dim newColor As Color Dim userName As String Dim notEnoughArguments As String = "Please fill out the fields" 'Click event for button Private Sub

无法找出为什么不选中文本框以及所选颜色
如果我没有输入颜色,它会标记“请输入字段”消息,但是如果我选择了颜色,但没有在“名称”文本框中输入任何内容,则它会继续并在msgbox中输出一个空白字符串

代码是:

 Dim newColor As Color
Dim userName As String
Dim notEnoughArguments As String = "Please fill out the fields"


'Click event for button
Private Sub enterBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles enterBtn.Click

    If (userName Is "") Then

        MsgBox(notEnoughArguments)

    ElseIf (userName Is "" And colorLtb.SelectedItem Is Nothing) Then

        MsgBox(notEnoughArguments)

    ElseIf (colorLtb.SelectedItem Is Nothing) Then

        MsgBox(notEnoughArguments)

    Else

        userName = txt1.Text
        Dim selectedColor As String = colorLtb.SelectedItem.ToString
        newColor = Color.FromName(selectedColor)
        Dim msgBoxText As String = "Hello " + txt1.Text + "." & vbCrLf + "Changing your color to " + selectedColor + "."
        MsgBox(msgBoxText)

        Me.BackColor = newColor

    End If


End Sub
对于字符串(如文本框内容),使用
String.IsNullOrWhitespace
作为测试。你也想要两个论点,对吗?因此,一个单独的声明应该可以:

If String.IsNullOrEmpty(userName) OrElse colorLtb.SelectedItem Is Nothing Then
    MessageBox.Show(notEnoughArguments)
    Return
End If

问题是
Dim userName As String
意味着变量没有任何内容,这与空字符串不同。我总是声明字符串并立即将它们设置为
String.Empty
以避免空引用异常,但使用
String.IsNullOrEmpty
是测试字符串变量内容的干净而可靠的方法。

通常在VB中测试相等性时,使用单个=而不是is

If (userName = "") Then
当无需测试时,您必须使用Is

If (userName Is Nothing) Then
IsNullOrEmpty结合了这两个测试。正如公认的答案所表明的那样:

If (String.IsNullOrEmpty(userName)) Then

意识到我只是在检查它们是否都完成了,但当将它们放入单独的if's和elseif时,它是否仍然不起作用编辑主帖子以显示新代码。不过还是有同样的问题。那应该是
。谢谢你的提示和解释。这真的很有帮助。我这样做了,但使用了“或”而不是“和”。现在它就像一个符咒。非常感谢你的帮助。再次解释一下,在开发以后的项目时,我肯定会继续这些规则。非常正确@NicoSchertler!我的错误是,冲向scrum电话,没有回读!事实上,这是一个
OrElse
,因为在这里有一点捷径是没有坏处的,因为如果第一个测试失败,就不需要运行第二个测试。