How to merge two multiline textboxes

2019-09-21 19:39发布

I need to combine two multi-line textboxes in vb net, like this:
textbox1:
a
b
c
d

textbox2:
1
2
3
4

textbox3:
a1
b2
c3
d4
Just a form with three textboxes. And a button to merge/combine/concatenate each value from t1 and t2, in t3.

One of my attempts:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

    For Each line In TextBox1.Lines
        For Each linex In TextBox2.Lines
            Me.TextBox3.Text += line & linex
            Me.TextBox3.Text += Environment.NewLine
        Next
    Next

End Sub

but result combination of lines (lines=linex) taken by two (a1,a2,a3,b1,b2,b3...)

2条回答
干净又极端
2楼-- · 2019-09-21 20:21

There are probably many ways you could do this. I have shown you one below but you would be assuming that textbox two contains the same amount of lines as textbox 1. It doesnt contain any validation but would do what you are asking.

See the comments to understand what is happening.

'Declare empty string for concatinating the text used in textbox 3
    Dim lsText As String = String.Empty
    'Loop for the count of lines in the textbox starting at an index of 0 for pulling data out
    For i As Integer = 0 To TextBox1.Lines.Count - 1
        'Check if lsText has already been assigned a value
        If lsText = String.Empty Then
            'If is has not then you know its the first so dont need a carriage return line feed simply take both values at that index
            lsText = TextBox1.Lines(i) & TextBox2.Lines(i)
        Else
            'Otherwise you want the new value on a new line
            lsText = lsText & vbCrLf & TextBox1.Lines(i) & TextBox2.Lines(i)
        End If
    Next
    'Set the textbox text to the finished concatination
    TextBox3.Text = lsText
查看更多
【Aperson】
3楼-- · 2019-09-21 20:39

I would use an integer as a counter in a loop that will extract the letter from each at the value of count, and increase count each time.

What you are trying to do is quite simple, so i won't provide any code - You won't learn efficiently that way.

Just know that you will need to filter newlines, know how many 'char' in each textbox, and use a loop. Or many other ways, but i think what i have hinted is easy and should be about 5 lines of code that you have somewhat already demonstrated.

Good luck. keep posting what you are trying, and i'll give help if i feel you are trying. Though now i'm going to bed.

查看更多
登录 后发表回答