2016-03-01 52 views
1

我需要使用For循環更改TextBox中的某些行。問題是,當我運行下面的代碼時,我得到一個IndexOfOfRangeException使用循環更改文本框中的文本

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
    For counter As Integer = 0 To TextBox1.Lines.Length = -1 
     TextBox1.Text = "some text" & "(" & """" & TextBox1.Lines(counter) & """" & ")" & vbCrLf 
    Next 
End Sub 

回答

0

首先

For counter As Integer = 0 To TextBox1.Lines.Length = -1 

應該

For counter As Integer = 0 To TextBox1.Lines.Length -1 

否則評估To爲布爾之後的部分。

TextBox1.Text = "some text" & "(" & """" & TextBox1.Lines(counter) & """" & ")" & vbCrLf 

您在文本框的完整文本設置爲這個新的字符串,而不是僅僅改變一行。

完成此任務的最簡單方法是將文本框的行復制到字符串數組中,更改該數組中的字符串並將其複製回來。

Dim tempArray as String() 
tempArray = TextBox1.Lines 
For counter = 0 to tempArray.Length -1 
    tempArray(counter) = "some text" & "(" & """" & tempArray(counter) & """" & ")" & vbCrLf 
Next 
TextBox1.Lines = tempArray