I've got a textbox control that only allows numeric input, including
negative numbers and decimal points. I was wondering if the following code
could be accomplished more efficiently with regular expressions:
' Inherited textbox that only allows numeric input
Public Class NumericTextBox
Inherits System.Windows.Forms.TextBox
Protected Overrides Sub OnKeyPress(ByVal e As
System.Windows.Forms.KeyPressEventArgs)
e.Handled = (Not Char.IsControl(e.KeyChar)) AndAlso _
(Not Char.IsNumber(e.KeyChar)) AndAlso _
(Not (Char.IsPunctuation(e.KeyChar) And _
(((e.KeyChar = ".") And
(Text.IndexOf(".") = -1)) Or _
((e.KeyChar = "-") And (SelectionStart
= 0)))))
End Sub
End Class
I suspect it could be done more efficiently with regular expressions, but I
have no idea how to begin constructing it. Could somebody provide an example
of a regular expression that accomplishes the same thing as the code above?
(i.e. the text must be all numeric, with an optional leading minus sign and
exactly zero or one decimal point)
Bonus kudos if you can replace the hard-coded "." and "-" with
international, system-specific characters.
Thanks,
Tim
Tim,
I will look into this in a bit. Until then, you may want to consider NOT
using the OnKeyPress method. You are not taking into account that the user
can paste values into the textbox negating the key press validation.
Cal
"Cali LaFollett" <cali@please_no_spam_visionized.com> wrote in message
news:eXGuqgk6BHA.1080@tkmsftngp02...
> Tim,
>
> I will look into this in a bit. Until then, you may want to consider NOT
> using the OnKeyPress method. You are not taking into account that the user
> can paste values into the textbox negating the key press validation.
>
> Cal
You may want to take a look at the thread titled "Number only Field..."
in the microsoft.public.dotnet.languages.csharp ng.
Regards,
Dan
It's kind of surprising that this seemingly simple problem has so many
gotchas to it.
Tim
"Cali LaFollett" <cali@please_no_spam_visionized.com> wrote in message
news:eXGuqgk6BHA.1080@tkmsftngp02...
Imports System.Threading.Thread
Imports System.Globalization
' Inherited textbox that only allows numeric input
Public Class NumericTextBox
Inherits System.Windows.Forms.TextBox
Private prevText As String
Private Shared nfi As NumberFormatInfo =
CurrentThread.CurrentUICulture.NumberFormat
Private Shared firstChars() As String = { _
nfi.NumberDecimalSeparator, _
nfi.NegativeSign, _
String.Empty}
Protected Overrides Sub OnTextChanged(ByVal e As EventArgs)
Dim result As Double
If (Double.TryParse(Text, NumberStyles.Any, nfi, result)) Then
prevText = Text
ElseIf (Array.IndexOf(firstChars, Text) = -1) Then
Dim selStart As Integer = SelectionStart
Text = prevText
SelectionStart = selStart
Else
prevText = Text
End If
End Sub
End Class
Hope that helps,
Tim