2014-10-19 101 views
0

請考慮我很新用VB.NET試圖讀取並回答我的問題顯示新線陣列中的每個元素

我有一個文本框,這需要與在一個逗號分隔的單詞列表時同一條線。當單擊按鈕時,字符串被分配給變量文本,然後我將其分割爲變量arrayText。 然後我遍歷它並在新行上顯示數組的每個元素。

我的代碼如下

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 

調試時我收到錯誤消息數組越界,但是當我刪除換行符(vbCrLf)它顯示我的文字,一個字一個字在一個MessageBox(其我用於調試),並在循環結束時它踢出相同的錯誤信息。

我在這裏做錯了什麼,有什麼改進建議?

回答

2

雖然walther的回答是對的,但我建議你使用List(Of String)For Each...Next循環。

一個列表更「現代」,大多數時候它比vb.net中的數組更受歡迎。您可以使用Environment.NewLine而不是vbCrLf。我不確定你想要做什麼,但我不認爲使用MsgBox是呈現分離單詞的最佳方式。這裏是我認爲你應該做的一個簡單的例子:

' 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 
1
For i = 0 To arrayText.Length - 1 Step 1 

最後一個元素索引爲length of array - 1

+0

謝謝你這麼多walter,我使用正確的過程來添加每一個字在新的行? – Marilee 2014-10-19 12:07:34

相關問題