Strings in Visual Basic

Start a new project named Names. Build the form as shown below:

  1. There is a labellabel with the words "Enter a name as Last,First"
  2. There is a text box textboxnamed TxtName.
  3. There is a labellabel named LblGreeting

name program

4. Write the code as shown below:

Note: When you double click on the text box the TxtName_TextChanged sub opens. This event doesn't tell us which key was pressed.
In the list of events for TxtName find the KeyPress event. You can delete the TextChanged event.

'Strings
Public Class Form1
    Private Sub TxtName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtName.KeyPress
        If e.KeyChar.Equals(Chr(13)) Then 'If they pressed Enter
            Dim First, Last As String
            Dim name As String = TxtName.Text
            Dim P As Integer = name.IndexOf(",") 'Find position of comma
            If P >= 0 Then
                First = name.Substring(P + 1) 'First name is everything AFTER the comma
                Last = name.Substring(0, P)  'Last name is everything BEFORE the comma
                LblGreeting.Text = "Hello " & First & " " & Last
            Else
                LblGreeting.Text = "Please put in a comma between first and last"
            End If
        End If
    End Sub
End Class

NEXT: Names: Other ways to do the same thing!