【发布时间】:2011-06-10 20:56:42
【问题描述】:
我想在输入时格式化文本框的内容。
我知道我可以在LostFocus 事件中执行此操作,但我希望在我打字时完成。有人对如何实施有任何建议吗?
【问题讨论】:
标签: .net vb.net winforms textbox
我想在输入时格式化文本框的内容。
我知道我可以在LostFocus 事件中执行此操作,但我希望在我打字时完成。有人对如何实施有任何建议吗?
【问题讨论】:
标签: .net vb.net winforms textbox
与其尝试自行安装,不如考虑使用专门设计用于处理格式化输入的控件。 具体来说,您需要MaskedTextBox 控件,它是现有文本框的增强版,允许您设置用于区分有效和无效输入的“掩码”。用户甚至可以在键入时获得视觉反馈。
您需要设置Mask property 来告诉控件您希望如何格式化其内容。所有可能的值都显示在链接的文档中。要显示货币,您可以使用类似:$999,999.00,它表示 0 到 999999 范围内的货币值。简洁的部分是货币、千位和小数字符在运行时会自动替换为它们的文化- 特定的等价物,使编写国际软件变得更加容易。
【讨论】:
Mask 属性。您不会将其设置为 1,000,000.00,因为 0 指定了一个介于 0 和 9 之间的 必需 数字。相反,您将使用 9(就像在我的示例中一样),这意味着数字或空格是 可选的 那里。这样,用户总是可以输入一个小于您的最大位置值的数字。
Dim strCurrency As String = "" 将可接受键调暗为布尔 = False
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) 处理 TextBox1.KeyDown If (e.KeyCode >= Keys.D0 And e.KeyCode = Keys.NumPad0 And e.KeyCode
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
【讨论】:
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
【讨论】: