qckmini6
qckmini6

Reputation: 124

VB.NET Add each words from textbox as new items in listbox

I want to add each words from textbox as new items in listbox and it worked, but the problem is that the textbox is multi lined so the code everytimes add the last word from a line with the next word in the next line in the same item.

Here is the code:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim words() As String
    Dim space() As Char = {" "c}
    'split each word by space
    words = TextBox1.Text.Split(words)
    Dim word As String
    For Each word In words
        'Add each word in to Listbox
        ListBox1.Items.Add(word)
    Next
End Sub

I tried this but it doesn't work:

Dim words() As String
    Dim space() As Char = {" "c}
    Dim xx As Char = vbNewLine
    'split each word by space
    words = TextBox1.Text.Split(words AndAlso xx)
    Dim word As String
    For Each word In words
        'Add each word in to Listbox
        ListBox1.Items.Add(word)
    Next

Finnaly fiexd:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim words() As String
    Dim space() As Char = {" "c, Microsoft.VisualBasic.vbCr, Microsoft.VisualBasic.vbLf}
    words = TextBox1.Text.Split(space, StringSplitOptions.RemoveEmptyEntries)
    For Each word As String In words
        ListBox1.Items.Add(word)
    Next
End Sub

Upvotes: 0

Views: 1494

Answers (2)

Steve
Steve

Reputation: 216353

Change your initialization of the space array to

Dim space() As Char = {" "c, Microsoft.VisualBasic.vbCr, Microsoft.VisualBasic.vbLf}

and when splitting add the RemoveEmptyEntries option

words = TextBox1.Text.Split(space, StringSplitOptions.RemoveEmptyEntries)

This will use both the carriage return and the line feed chars as separators while the RemoveEmptyEntries option will clear the results from the wrong empty "word" produced between the carriage return and line feed as well any empty lines at the end of your textbox.

Upvotes: 3

Steve
Steve

Reputation: 5545

If you want to split by spaces but the line return is messing with you, remove the line return.

words = TextBox1.Text.Replace(chr(10),"").replace(chr(13),"").Split(words)

EDIT:

Wait, I think you posted some wrong code. Not sure how yours was working. It should have been like this.

words = TextBox1.Text.Replace(chr(10),"").replace(chr(13),"").Split(" "c)

Upvotes: 1

Related Questions