【问题标题】:How do you concatenate strings from two TextBoxes?你如何连接来自两个文本框的字符串?
【发布时间】:2014-03-17 14:34:39
【问题描述】:

例如在这段代码中

Public Class Form1

    Dim a As Object
    Dim b As Object
    Dim c As Object

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        a = Val(TextBox1.Text)
        b = Val(TextBox2.Text)
        c = Val(TextBox3.Text)

        TextBox3.Text = a + b

       ' TextBox4.Text = "a + b = c"
    End Sub

End Class

如何让 TextBox4.Text 显示数字、(=) 符号和 (+) 符号,即

TextBox1.Text = "2" and TextBox2.Text = "3" and TextBox3.Text = "5"

我怎样才能使 TextBox4.Text = "2 + 3 = 5"

(字符串不是值)

【问题讨论】:

  • 你在问如何连接字符串?
  • 我认为他是。它可能看起来像这样: TextBox4.Text = ""+ a + " + " + b + " = " + c + ""
  • @FrankTudor 在 VB.NET 中连接字符串时始终使用&,因为它清楚地表明了您的意图与+
  • 好的,我明白了....谢谢。

标签: vb.net string concatenation


【解决方案1】:

您可以使用&+ 运算符连接字符串,如下所示:

TextBox4.Text = TextBox1.Text & " + " & TextBox2.Text & " = " & TextBox3.Text

在 VB.NET 中,& 运算符是字符串连接的首选,但是,只要您有 Option Strict On+ 运算符就可以安全地使用:

TextBox4.Text = TextBox1.Text + " + " + TextBox2.Text + " = " + TextBox3.Text

或者,对于更复杂的连接,比如这个,你可能会发现使用String.Format 更容易,就像这样:

TextBox4.Text = String.Format("{0} + {1} = {2}", TextBox1.Text, TextBox2.Text, TextBox3.Text)

【讨论】:

  • 我会使用 & 而不是 + 来连接... TextBox4.Text = TextBox1.Text & " + " & TextBox2.Text & " = " & TextBox3.Text
  • 我认为 + 是对的....看这里stackoverflow.com/questions/8630146/…
  • 如果你想获得更多的声誉,我建议你的答案更解释、清晰和透彻。我已经编辑了您的答案,以向您展示我的意思的示例。我发现,经常彻底和乐于助人与正确一样重要。
  • @FrankTudor 不对……看这里stackoverflow.com/questions/1088053/…。您的链接问题甚至使用了旧版 VB6 函数,例如 MsgBox,应该避免使用 .NET 的 MessageBox.Show()
猜你喜欢
  • 2013-02-05
  • 2023-03-22
  • 1970-01-01
  • 2011-08-29
  • 2011-11-04
  • 2022-11-16
相关资源
最近更新 更多