0

Please consider I am very new with VB.NET when attempting to read and answer my question

I have a textbox that takes in a list of words separated with a comma on the same line. When button is clicked string gets assigned to variable text and I then split it to variable arrayText. Then I loop over it and display each element of array on new line.

My code looks as follows

 Dim text As String
 Dim arrayText() As String

    text = TextBox1.Text
    arrayText = text.Split(",") 'every "," generates new array index, removes ","

    text = ""

    For i = 0 To arrayText.Length Step 1
        text = arrayText(i) & vbCrLf
        MsgBox(text)
    Next

When debugging I get error message array out of bounds, however when I remove the newline character (vbCrLf) it displays my text, word for word in a messagebox (which I am using for debugging) and at the end of the loop it kicks out with same error message.

What am I doing wrong here, any improvement suggestions?

2 Answers 2

2

Though walther answer is right, i suggest you to use a List(Of String) and a For Each...Next loop.

A list is more "modern" and most of the times it is preferred over an array in vb.net. You can use Environment.NewLine instead of vbCrLf. I'm not sure what exactly you want to do, but I dont think that using a MsgBox is the optimal way to present the seperated words. Here is a simple example of what I think you should do :

' Hold the text from the text box.
Dim FullText As String = TextBox1.Text
Dim SeperatedWords As New List(Of String)
' ToList function converts the array to a list.
SeperatedWords = FullText.Split(",").ToList
' Reset the text for re-presentation.
FullText = ""
' Goes through all the seperated words and assign them to FullText with a new line.
For Each Word As String In SeperatedWords
    FullText = FullText & Word & Environment.NewLine
Next
' Present the new list in the text box.
TextBox1.Text = FullText
Sign up to request clarification or add additional context in comments.

Comments

1
For i = 0 To arrayText.Length - 1 Step 1

Last element has index of length of array - 1.

1 Comment

thank yo so much walter, am I using the correct procedure to add each word on new line?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.