1

I have 2 textbots and first one has several lines. I want to edit each line in textbox 1 to add the text from textbox 2 to each line.

So, if textbox1 has the follow lines:

i am
you are
he is
she is

and the textbox 2 has text: John

then the textbox1 would become

i am John
you are John
he is John
she is John

I tried this:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    For Each strLine As String In TextBox1.Text.Split(vbNewLine)
        strLine += " " + TextBox2.Text
    Next
End Sub

But no success, any help?

2 Answers2

2

You can modify directly the strLine because its not affecting the textbox value. You need to create a new variable and then use it to replace the Textbox1.Text

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim newText as New String()
    For Each strLine As String In TextBox1.Text.Split(vbNewLine)
        newText &= strLine & " " & TextBox2.Text & Environment.NewLine
    Next

Textbox1.Text = newText
End Sub

Check the syntax because i don't use Vb.net much.

Luis Tellez
  • 2,785
  • 1
  • 20
  • 28
  • 2
    That last line will work better without the semicolon at the end. Also, it makes no difference here, but VB.NET has a & operator specifically for string concatenation. If you try to concatenate strings with other data types using +, the compiler will sometimes guess incorrectly at what you meant. (See http://stackoverflow.com/questions/734600/the-difference-between-and-for-joining-strings-in-vb-net.) – pmcoltrane May 02 '14 at 14:39
  • 1
    Thanks @pmcoltrane i'm mostly a C# guy – Luis Tellez May 02 '14 at 14:49
0

You could also use the Lines property of the textbox in this way.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim newText As New List(Of String)
    For Each strLine As String In TextBox1.Lines
        newText.Add(strLine & " " & TextBox2.Text)
    Next

    Textbox1.Lines = newText.ToArray
End Sub

Be sure you don't try to work directly on the lines property. You had to work on a new collection and then replace the lines property with the new one.

Marco Guignard
  • 613
  • 3
  • 9