在文本框中键入数字时,请使用逗号和美分格式

时间:2019-05-23 06:34:50

标签: vb.net

专业开发人员,我想问你一些问题。我希望你能帮助我。我的问题是:我有一个名为“ txtUnitPrice”的文本框,当我在上面输入数字时,它会自动生成该数字的逗号和小数,例如:当我键入数字“ 4”时,它将显示“ 4.00”,当我键入“ 1000”时,它将显示“ 1,000.00”,我该怎么办,请帮帮我。

我在这里尝试了许多与我的问题有关的问题,但是没有一个可以帮助我。

这是我的代码:

Private Sub txtUnitPrice_TextChanged(sender As Object, e As EventArgs) Handles txtUnitPrice.TextChanged
    Dim input As Double = Double.Parse(txtUnitPrice.Text)
    Dim inputNumWithCommas As String = input.ToString("N0", CultureInfo.InvariantCulture)
    txtUnitPrice.Text = inputNumWithCommas
End Sub

上面的代码不是我想要的输出。请帮我谢谢。

1 个答案:

答案 0 :(得分:0)

目前,一种简单的方法是在文本框下方添加一个按钮,然后在按下按钮时以及在向txtUnitPrice输入数字后使用此按钮

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        txtUnitPrice.Text = FormatCurrency(txtUnitPrice.Text)
End Sub

无需按钮即可实时更新的另一种方式是

Dim strCurrency As String = ""
Dim acceptableKey As Boolean = False

Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtUnitPrice.KeyDown
        If (e.KeyCode >= Keys.D0 And e.KeyCode <= Keys.D9) OrElse (e.KeyCode >= Keys.NumPad0 And e.KeyCode <= Keys.NumPad9) OrElse e.KeyCode = Keys.Back Then
            acceptableKey = True
        Else
            acceptableKey = False
        End If
    End Sub

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtUnitPrice.KeyPress
        ' Check for the flag being set in the KeyDown event.
        If acceptableKey = False Then
            ' Stop the character from being entered into the control since it is non-numerical.
            e.Handled = True
            Return
        Else
            If e.KeyChar = Convert.ToChar(Keys.Back) Then
                If strCurrency.Length > 0 Then
                    strCurrency = strCurrency.Substring(0, strCurrency.Length - 1)
                End If
            Else
                strCurrency = strCurrency & e.KeyChar
            End If

            If strCurrency.Length = 0 Then
                txtUnitPrice.Text = ""
            ElseIf strCurrency.Length = 1 Then
                txtUnitPrice.Text = "0.0" & strCurrency
            ElseIf strCurrency.Length = 2 Then
                txtUnitPrice.Text = "0." & strCurrency
            ElseIf strCurrency.Length > 2 Then
                txtUnitPrice.Text = strCurrency.Substring(0, strCurrency.Length - 2) & "." & strCurrency.Substring(strCurrency.Length - 2)
            End If
            txtUnitPrice.Select(TextBox1.Text.Length, 0)

        End If
e.Handled = True
    End Sub

可能想改变一些东西,但是请随便玩。