检查是否为null VB.NET

时间:2014-09-11 09:05:15

标签: 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 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

2 个答案:

答案 0 :(得分:2)

对于字符串(如文本框内容),请使用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是一种干净且可靠的方法来测试字符串变量的内容。

答案 1 :(得分:0)

通常要在VB中测试相等性,可以使用单个=而不是Is

If (userName = "") Then

在测试Nothing时,您必须使用Is

If (userName Is Nothing) Then

IsNullOrEmpty结合了两种测试。正如公认的答案所示:

If (String.IsNullOrEmpty(userName)) Then