Bcon615 Bcon615 - 1 year ago 63
Vb.net Question

Search string for a certain character

I'm creating a Windows Forms form that requires a user to enter a part number, such as "XY12345E678". Then, with an

-statement have the program search the 7th position and do some code based on what character is in that position. In this case it will either be an "E" or "F".

For example:

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 '''
''' Do some code '''

Answer Source

If you find yourself writing long If...ElseIf... ElseIf... statements then you should consider using Select Case instead, like this:

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

    ' the part number is too short
End If

You don't actually need to use = in the case clauses, but if you want to you can use Case Is = "E" etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download