我想在输入时格式化文本框的内容。
我知道我可以在LostFocus
事件中执行此操作,但我希望在输入时完成此操作。有没有人对如何实现这个有任何建议?
答案 0 :(得分:1)
不要试图自己设置这个,而是考虑使用专门设计用于处理格式化输入的控件。 具体来说,您需要MaskedTextBox
控件,这是现有文本框的增强版本,允许您设置用于区分有效输入和无效输入的“掩码”。用户甚至可以在输入时获得视觉反馈。
您需要设置Mask
property以告诉控件您希望如何格式化其内容。所有可能的值都显示在链接的文档中。要显示金钱,您可以使用类似:$999,999.00
,表示0到999999范围内的货币值。整洁的部分是货币,千分之一和十进制字符在运行时自动替换为他们的文化特定的等价物,使编写国际软件更容易。
答案 1 :(得分:0)
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
答案 2 :(得分:-1)
Dim strCurrency As String =“” Dim acceptableKey As Boolean = False
Private Sub TextBox1_KeyDown(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyEventArgs)处理TextBox1.KeyDown 如果(e.KeyCode> = Keys.D0和e.KeyCode< = Keys.D9)OrElse(e.KeyCode> = Keys.NumPad0和e.KeyCode< = Keys.NumPad9)OrElse e.KeyCode = Keys 。然后 acceptableKey = True 其他 acceptableKey =假 万一 结束子
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 结束子
@stynx