使用循环更改文本框中的文本
Change text in a TextBox using a Loop
我需要使用 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
第一个
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
我需要使用 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
第一个
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