Phantom
Phantom

Reputation: 51

How to add each line from 2 richtextboxes together? [VB.NET]

Hi how can i add each line from richtextbox1.text to richtexbox2.text and display them in Richtextbox3.text Sorry for asking such a "simple" question but im fairly new to VB.net Any help is much appriciated,

//Richtextbox1.text 
   Super
   Strong
   Smart

//Richtextbox2.text
   Dog
   Cat
   Man



//Richtextbox3.text
     Super Dog
     Strong Cat
     Smart Man

Upvotes: 0

Views: 66

Answers (1)

Steve
Steve

Reputation: 216293

Start a loop over the Lines property of the first richTextBox, read the line at each loop and if the second richTextBox has a line in the same index combine them together. Finally at each loop add the resulting string to the third richTextBox

For x As Integer = 0 To richTextBox1.Lines.Count - 1

    Dim combinedLine As String = richTextBox1.Lines(x)
    If x <= richTextBox2.Lines.Count - 1
        combinedLine = combinedLine & " " & richTextBox2.Lines(x)
    End If
    richTextBox3.AppendText(combinedLine & Environment.NewLine)
Next

Consider also, that if you have a lot of lines, it is better to use a StringBuilder class, accumulate the text in this class and append all in a single call

Dim sb = New StringBuilder()
For x As Integer = 0 To richTextBox1.Lines.Count - 1

    sb.Append(richTextBox1.Lines(x))
    If x <= richTextBox2.Lines.Count - 1
        sb.Append(" " & richTextBox2.Lines(x))
    End If
    sb.AppendLine()
Next
richTextBox3.AppendText(sb.ToString())

Upvotes: 1

Related Questions