如何在文本框中始终将美元符号添加到值

时间:2014-12-27 13:56:26

标签: vb.net

我想在用户添加任意​​数字时始终在文本框中添加$符号。

我的代码看起来像这样,但它不起作用:

Private Sub capitalTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles capitalTB.TextChanged
    Dim cleanTXT As String
    If capitalTB.Text.StartsWith("$") = False Then
        cleanTXT = "$" & capitalTB.Text
        capitalTB.Text = cleanTXT
    End If
End Sub

当我输入第二个数字时,它会变成这样: enter image description here

任何帮助都会很棒。

3 个答案:

答案 0 :(得分:2)

Private Sub capitalTB_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles capitalTB.TextChanged
    If capitalTB.Text.StartsWith("$") = False Then
        Dim SelStart As Integer

        SelStart = capitalTB.SelectionStart
        capitalTB.Text = "$" & capitalTB.Text
        capitalTB.SelectionStart = SelStart + 1
    End If
End Sub

尝试上面的代码并为您的学习:当您重置文本框的文本时,您丢失的是光标位置,它将光标放在文本框的开头(这是插入的$之前的事实)。我首先将光标位置存储在变量中,然后将其分配回文本框,增加1,因为现在还有另一个字母$。

答案 1 :(得分:0)

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles capitalTB.TextChanged
    Dim cleanTXT As String
    If capitalTB.Text.StartsWith("$") = False Then
        cleanTXT = "$" & Replace(capitalTB.Text, "$", "")
        capitalTB.Text = cleanTXT
    End If
End Sub

答案 2 :(得分:0)

回答了我自己的问题,用这个解决了

 Private Sub capitalTB_Validating(ByVal sender As Object, _
                                    ByVal e As System.ComponentModel.CancelEventArgs) Handles capitalTB.Validating
        Dim currency As Decimal

        'Convert the current value to currency, with or without a currency symbol.
        If Not Decimal.TryParse(Me.capitalTB.Text, _
                                Globalization.NumberStyles.Currency, _
                                Nothing, _
                                currency) Then
            'Don't let the user leave the field if the value is invalid.
            With Me.capitalTB
                .HideSelection = False
                .SelectAll()

                MessageBox.Show("Please enter a valid capital amount.", _
                                "Invalid Capital", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Error)

                .HideSelection = True
            End With

            e.Cancel = True
        End If
    End Sub

    Private Sub capitalTB_Validated(ByVal sender As Object, _
                                   ByVal e As System.EventArgs) Handles capitalTB.Validated
        'Display the value as local currency.
        Me.capitalTB.Text = Decimal.Parse(Me.capitalTB.Text).ToString("c")
    End Sub

感谢@Avijit货币蒙面。