2016-04-27 184 views
-2

我正在創建一個要求用戶輸入部件號的Windows Forms表單,例如「XY12345E678」。然後,使用if-語句將程序搜索第7個位置,並根據該位置中的字符做一些代碼。在這種情況下,它將是「E」或「F」。某個字符的搜索字符串

例如:

 Dim partNumber as String 
     partNumber = textboxPartNumber.Text 
     Dim seventhPosition as String 
     seventhPosition = partNumber.Substring(7, 1) 

     If seventhPosition *is an "E"* 
     ''' Do some code ''' 
     ElseIf seventhPosition *is an "F"* 
     ''' Do some code ''' 
     Else 
     ''' Do some code ''' 
+2

它是什麼你卡住了?您與'='比較 – BanksySan

+0

@BanksySan if語句的條件。是否就像「如果第七個位置=」E「那麼簡單...然後...? – Bcon615

+0

是的。Google也會這麼說![** Visual Basic **中的比較運算符](https://msdn.microsoft.com /en-us/library/215yacb6.aspx)。 –

回答

1

如果你發現自己寫長If...ElseIf... ElseIf...語句,那麼你應該考慮使用Select Case代替,就像這樣:

Dim partNumber As String = textboxPartNumber.Text 

If partNumber.Length >= 7 Then 
    Dim seventhPosition As String = partNumber.Substring(7, 1) 
    Select Case seventhPosition 
     Case "E" 
      ' some code 
     Case "F" 
      ' some code 
     Case Else 
      ' it is not an "E" or "F" 
    End Select 

Else 
    ' the part number is too short 
End If 

您實際上並不需要使用=在案件條款,但如果你想要你可以使用Case Is = "E"

0

你可以用這個試試...

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
      Dim partNumber As String 
      partNumber = textboxPartNumber.Text 
      Dim seventhPosition As String 
      seventhPosition = partNumber.Substring(7, 1) 

      If seventhPosition = "E" Then 
       MsgBox(seventhPosition) 

      ElseIf seventhPosition = "F" Then 
       MsgBox(seventhPosition) 
      Else 
       MsgBox("others") 
      End If 
     End Sub 
0
  Dim partNumber As String 
      partNumber = textboxPartNumber.Text 

      Dim seventhPosition As String 
      seventhPosition = partNumber.Chars(7) 

      If seventhPosition = "E" OrElse seventhPosition = "F" Then 
       'Do something 
      End If