How can I format a value as money (ex. 123,456.50) in a textbox while typing?
I want to format the contents of my textbox while typing.
I know that I can do this in LostFocus
event, but I want it to be done while I am typing. Does anyon开发者_C百科e have any suggestions on how to implement this?
Rather than trying to rig this up yourself, consider using a control that's specifically designed to handle formatted input. Specifically, you need the MaskedTextBox
control, which is an enhanced version of the existing textbox that allows you to set a "mask" used to distinguish between valid and invalid input. The user even gets visual feedback as they type.
You'll need to set the Mask
property to tell the control how you want its contents to be formatted. All of the possible values are shown in the linked documentation. To display money, you would use something like: $999,999.00
, which represents a currency value in the range of 0 to 999999. The neat part is that the currency, thousandth, and decimal characters are automatically replaced at run-time with their culture-specific equivalents, making it much easier to write international software.
Private Sub TBItemValor_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TBItemValor.KeyPress
If (Char.IsDigit(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False AndAlso Char.IsPunctuation(e.KeyChar) = False) OrElse Not IsNumeric(Me.TBItemValor.Text & e.KeyChar) Then
e.Handled = True
End If
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 TextBox1.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 TextBox1.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
TextBox1.Text = ""
ElseIf strCurrency.Length = 1 Then
TextBox1.Text = "0.0" & strCurrency
ElseIf strCurrency.Length = 2 Then
TextBox1.Text = "0." & strCurrency
ElseIf strCurrency.Length > 2 Then
TextBox1.Text = strCurrency.Substring(0, strCurrency.Length - 2) & "." & strCurrency.Substring(strCurrency.Length - 2)
End If
TextBox1.Select(TextBox1.Text.Length, 0)
End If
e.Handled = True End Sub
@stynx
精彩评论