Search code examples
vb.netmultilinemultilinestring

Editing multiple lines in TextBox


I want my program to take a string entered into a TextBox and then convert it in a pattern. Here is my current code:

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
    For Each line As String In TextBox1.Lines
        TextBox1.Text.Insert(0, """")
        TextBox1.Text.Insert((TextBox1.Text.Length), """")
        TextBox2.AppendText(line & vbCrLf)
    Next
End Sub

I don't want these changes to be done to the entire TextBox, but to each individual line. So

1111
1111

would turn into

"1111"
"1111"

instead of

"1111
1111"

Solution

  • You aren't going to be able to for-each it, so you would have to loop through your Lines collections. Easier to do this backwards, since inserting text will change index positions and so on, so try it this way:

    For i As Integer = TextBox1.Lines.Count - 1 To 0 Step -1
      If TextBox1.Lines(i).Length > 0 Then
        Dim startPos As Integer = TextBox1.GetFirstCharIndexFromLine(i)
        TextBox1.Select(startPos, TextBox1.Lines(i).Length)
        TextBox1.SelectedText = String.Format("{0}{1}{2}", """", TextBox1.Lines(i), """")
      End If
    Next