2014-09-11 201 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