J. Leo J. Leo -4 years ago 136
Vb.net Question

Split words in textboxes removing whitespaces

I'm trying to separate the words but there's whitespaces remaining in

FirstName
and
MiddleName
.

See screenshot:
Sample image

Here's my code:

Dim str As String = ListView1.Items(ListView1.SelectedIndices(0)).SubItems(2).Text
Dim splitStr As String() = str.Split(","c)
txtLastName.Text = splitStr(0).ToString()
txtFirstName.Text = splitStr(1).ToString()
txtMiddleInitial.Text = splitStr(2).ToString()


Is my code missing something?

Answer Source

To remove white-space characters from the start and end of a String I would use String.Trim:

Removes all leading and trailing white-space characters from the current String object.

To do this in your code simply append .Trim() to the end of your String:

Dim str As String = ListView1.Items(ListView1.SelectedIndices(0)).SubItems(2).Text
Dim splitStr As String() = str.Split(","c)
txtLastName.Text = splitStr(0).ToString().Trim()
txtFirstName.Text = splitStr(1).ToString().Trim()
txtMiddleInitial.Text = splitStr(2).ToString().Trim()

As a side note since splitStr(.) is already a String you don't need to use ToString():

txtLastName.Text = splitStr(0).Trim()
txtFirstName.Text = splitStr(1).Trim()
txtMiddleInitial.Text = splitStr(2).Trim()

To test, this was my code:

Dim str As String = "LOWELL, JOHN, F"
Dim splitStr As String() = str.Split(","c)

TextBox1.Text = splitStr(0)
TextBox2.Text = splitStr(1)
TextBox3.Text = splitStr(2)

TextBox4.Text = splitStr(0).Trim()
TextBox5.Text = splitStr(1).Trim()
TextBox6.Text = splitStr(2).Trim()

This is my output:

enter image description here

The TextBox order is the same as the code. You can see where the white-space has been removed from the bottom set using .Trim().

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