Strings in Visual Basic

Continue with the name project.

name program

Rewrite the code as shown below:

'Strings: Split name into first and last
Public Class Form1
    Private Sub TxtName_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtName.KeyPress
        If e.KeyChar.Equals(Chr(13)) Then
            Dim Txt As String = Me.TxtName.Text
            Dim Parts As String()
            Parts = Txt.Split(",")
            Me.TxtLast.Text = Parts(0)
            Me.TxtFirst.Text = Parts(1)
        End If
    End Sub
End Class
Note: If the user did not put in a comma, we will get an array out of bounds error when we refer to Parts(1). We can correct for this by modifying the code. We can either check to be sure there is a comma before the split, or check to make sure that length is 2 or more before trying to display Part(1):
Dim Parts As String()
If Txt.Contains(",") Then
   Parts = Txt.Split(",")
   Me.TxtLast.Text = Parts(0)
   Me.TxtFirst.Text = Parts(1)
End If 'contains comma

NEXT: Validating Strings