我从几乎相同的问题开始,但我确实关心能够粘贴。在网上搜索如何做到这一点时,我发现我真的应该处理:
- 句点或逗号作为十进制指示符,具体取决于您的操作系统的设置方式。
- 只允许符合模式的按键,同时仍然允许光标控制字符,如箭头和退格。
- 只允许粘贴到符合模式的 TextBox 中。我选择了这样一种方式,在粘贴时,代码将粘贴的文本视为正在键入文本,因此将“a1b.c2d,e3f.g4h,i5j”粘贴到 TextBox 将显示为“1.2345”如果句点是您的十进制指示符,如果逗号是您的十进制指示符,则为“12,345”。
我尝试了 MaskedTextBox 并且真的不喜欢它,因为它强制执行小数点位置,我真的只是希望能够自由填写任何数字。我使用 RegEx 进行模式匹配可能有点过火了,但现在我应该能够在几乎任何地方重用这段代码。
Public Class frmMain
Dim RegexValidator As System.Text.RegularExpressions.Regex
Dim FormLoaded As Boolean = False
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim RegexDecimalPattern As String = Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
RegexDecimalPattern = IIf(RegexDecimalPattern = ".", "\.", RegexDecimalPattern)
RegexValidator = New System.Text.RegularExpressions.Regex("^\d*" & RegexDecimalPattern & "?\d*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase)
FormLoaded = True
End Sub
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
' Code below is based on
' http://www.vbforums.com/showthread.php?626378-how-to-validate-textbox-allows-only-numeric-and-decimal-in-vb-net
' but was modified to be based on Regex patterns.
'
' Note that:
' KeyPress event validation covers data entry as it is being typed.
' TextChanged event validation covers data entry by cut/pasting.
If Char.IsControl(e.KeyChar) Then
'Allow all control characters.
Else
Dim Text = Me.TextBox1.Text
Dim SelectionStart = Me.TextBox1.SelectionStart
Dim SelectionLength = Me.TextBox1.SelectionLength
Text = Text.Substring(0, SelectionStart) & e.KeyChar & Text.Substring(SelectionStart + SelectionLength)
If Not RegexValidator.IsMatch(Text) Then e.Handled = True
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
' If default text is used in a textbox, a TextChanged event occurs before
' RegexValidator is initialized during the Form Load, so we need to check.
If FormLoaded Then
' Note that:
' KeyPress event validation covers data entry as it is being typed.
' TextChanged event validation covers data entry by cut/pasting.
Dim Text = Me.TextBox1.Text
Dim ValidatedText As String = ""
Dim KeyChar As Char
For Each KeyChar In Text
If RegexValidator.IsMatch(ValidatedText + KeyChar) Then ValidatedText += KeyChar
Next
If (ValidatedText.Length > 0) And (TextBox1.Text <> ValidatedText) Then
Me.TextBox1.Text = ValidatedText
Me.TextBox1.SelectionStart += ValidatedText.Length
End If
End If
End Sub
End Class