Search code examples
vb.nettextboxrenamecyclelines

Change text in a TextBox using a Loop


I need to change some lines in a TextBox using a For loop. The problem is that when I run the following code I get an 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

Solution

  • First

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

    should be

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

    Otherwise it evaluates the part after To as a boolean.

    Second

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

    you are setting the complete text of the textbox to this new string instead of just changing one line.

    The easiest way to do this task would be to copy the lines of the textbox to a string array, change the strings in that array and copy it back.

    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