2014-09-11 134 views
0

遇到问题,为什么这不会检查文本框以及选定的颜色。
如果我没有放置颜色,它会标记“请输入字段”消息,但是如果我确实选择了一种颜色,但不在名称文本框中输入任何内容,则它会继续并在msgbox中输出一个空白字符串。检查是否为空VB.NET

代码是:

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 
+0

发现我只检查,他们俩都做了,但把它们当进入单独的,如果我们从一个ELSEIF它仍然无法正常工作? - 编辑主文章以显示新代码。尽管如此,仍然有同样的问题。 – 2014-09-11 09:08:37

回答

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是一种干净而健壮的方式来测试字符串变量的内容。

+0

这应该是一个'或'。 – 2014-09-11 09:17:29

+0

感谢您的提示和解释。真的很有帮助。我已经这样做了,但用'或'而不是'和'。它现在像一个魅力。非常感谢您的帮助。再次说明,在开发后期项目时,我一定会继续这些规则。 – 2014-09-11 09:21:11

+0

非常正确@NicoSchertler!我的错误是,匆忙赶到scrum的电话,并没有回头看!事实上,把它变成了“OrElse”,因为它从来没有受到过伤害,因为如果第一次测试失败了,就没有必要跑第二次了。 – 2014-09-11 09:24:54

0

通常以测试VB平等,你使用一个=而非是

If (userName = "") Then 

当没有测试,你必须使用是

If (userName Is Nothing) Then 

IsNullOrEmpty结合了测试。作为接受的答案提示:

If (String.IsNullOrEmpty(userName)) Then