2014-03-26 149 views
0

所以即時嘗試讓這個代碼工作,但它不返回代碼的如果喜歡部分 任何值。我不知道爲什麼會發生這種情況。If Like語句沒有輸出?

Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click 
    'display color button click event procedure should display the color of the item 
    'whos item number is entered by the user. 

    'all item numbers contain exactly seven characters 
    'all items are available in four colors: blue, green, red, and white. 
    'the fourth character in the item number indicates the items color 
    'as follows: B or b indicates blue etc 
    'if the item number does not contain 7 charactors OR 
    'if the forth character is not one of the valid color characters, 
    'the procedure should display the appropriate message 

    If txtItem.Text Like "###[bBgGrRrwW]###" Then 
     If txtItem.Text.Contains("bB") Then 
      lblColor.Text = "Blue" 
     ElseIf txtItem.Text.Contains("gG") Then 
      lblColor.Text = "Green" 
     ElseIf txtItem.Text.Contains("rR") Then 
      lblColor.Text = "Red" 
     ElseIf txtItem.Text.Contains("Ww") Then 
      lblColor.Text = "White" 
     End If 
    ElseIf txtItem.Text IsNot "###[bBgGrRwW]###" Then 
     MessageBox.Show("Bad Job", "Color Project", MessageBoxButtons.OKCancel, 
         MessageBoxIcon.Information) 
    End If 
End Sub 
+0

什麼是'txtItem.Text'價值? – Steve

+0

確保你明白[Like'的作用是什麼](http://msdn.microsoft.com/en-us/library/swf8kaxw.aspx),[IsNot'的作用](http://msdn.microsoft.com/zh-cn/ com/en-us/library/t3bat82c.aspx)和[Contains'包含的內容](http://msdn.microsoft.com/zh-cn/library/dy85x1sa.aspx)。 – GSerg

+0

txtItem.Text的值是用戶輸入到文本框中的值。我試圖用類似的語句來驗證文本。據我所知,這應該起作用。 – 0000

回答

4

如果你有.Contains("bB"),你問它來檢查,如果字符串包含bB,即兩個字符。你真正想要做的是檢查它是否包含B,並忽略角色的情況。雖然Contains沒有一個不區分大小寫的選項,IndexOf作用:String.IndexOf Method (String, StringComparison),所以你可以使用

If txtItem.Text.IndexOf("B", StringComparison.OrdinalIgnoreCase) >= 0 Then 
+0

或者你可以做'如果txtItem.Text.ToLower.Contains(「b」)然後'我發現更容易閱讀 – Pacane

+0

@Pacane,這在所有情況下都不起作用(文化),所以使用IndexOf的重載'方法更安全。有關更多信息,請參閱[土耳其問題](http://blog.codinghorror.com/whats-wrong-with-turkey/)。 –

+0

Ohhhhhh哇,非常感謝!你們是最棒的! – 0000