首页 > 解决方案 > 如何在 VB.NET 中的每个文本框行之后添加文本

问题描述

我到处寻找,我找不到方法。我想找到一种在每个文本框行之后添加文本的方法,但我找不到这样做的方法。我有一个文本框1:

example1
example2
example3
And so on...

和另一个带有@gmail.com 的textbox2

我希望将 textbox2 添加到 textbox1 中每一行的末尾,例如:

example1@gmail.com
example2@gmail.com
example3@gmail.com
And so on...

有什么办法吗?提前致谢。

标签: vb.netvisual-studio

解决方案


此解决方案简洁,并删除了空行。

Private Function appendTextToOtherTextLines(textToAppend As String, otherText As String) As String
    Return String.Join(Environment.NewLine, otherText.
                       Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries).
                       Select(Function(s) s & textToAppend))
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TextBox3.Text = appendTextToOtherTextLines(TextBox2.Text, TextBox1.Text)
End Sub

这是您的示例

在此处输入图像描述

如果你有一个空行,它会在结果字符串中被删除

在此处输入图像描述

当然,您可以改写原始文本框,但请注意不要单击两次按钮!

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TextBox1.Text = appendTextToOtherTextLines(TextBox2.Text, TextBox1.Text)
End Sub

其他选项是一个事件处理程序,当在新行的末尾按回车时,它会自动发生这种情况。这仅在您主动手动输入行时才有用。

Private Sub TextBox1_KeyUp(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyUp
    If e.KeyCode = Keys.Enter Then
        TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 2) & TextBox2.Text & Environment.NewLine
        TextBox1.SelectionStart = TextBox1.Text.Length
    End If
End Sub

(此选项在按 Enter 时需要一些纪律)


推荐阅读