By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,133 Members | 1,092 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,133 IT Pros & Developers. It's quick & easy.

Numeric Textbox Code

P: n/a
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely reading them all - but I think I have a differing opinion of how I want to handle the 'user experience' in the application I'm creating. While I know I could allow the user to enter in number and alpha text - in a text box - and then tell them when the execuate a command "This is not numeric data", I would rather not allow them to enter alpha data - to begin with.

I've posted the below code from a page someone suggested. It is from a William Ryan. I have used it - it does work - but I run into two problems. One, the user cannot use the backspace key and two, it allows someone to enter another "." - decimal. The code author realizes this and says, "The use above will allow all valid numbers as well as decimals. It wouldn't be very difficult to expand upon this to verify that you don't have two decimal in the number, allow for currency characters etc." However - to be quite honest - I don't follow what the code is even doing. Can someone clarify what it is doing and how one would modify it to allow for only one decimal? (Bernie Yaeger I did read your post as well - if you could let me know how I could download your code/control - I would love to see it) Please see William's code below (link: http://www.knowdotnet.com/articles/n...textboxes.html

Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPres

Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar
Dim isDecimal As Boolean = e.KeyChar.ToString = ".
If Not isKey And Not isDecimal The
e.Handled = Tru
End I
End Sub
Nov 20 '05 #1
Share this Question
Share on Google+
11 Replies


P: n/a
Hi Keith,

I've read your post. I'm a bit busy now but I will either .zip the code to
you or contact you and get it to you in another manner. I will get this
done hopefully sometime this weekend, Mon the latest. I will try to include
a doc explaining whatever might need explanation. I actually have 2
controls, as I may have told you - one for integers and one for currency.

But - I need to have an email address or an ftp location to send it to -
please get back to me with this at your soonest convenience. You can email
me directly at be*****@cherwellinc.com.

Bernie

"Keith" <an*******@discussions.microsoft.com> wrote in message
news:BA**********************************@microsof t.com...
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely
reading them all - but I think I have a differing opinion of how I want to
handle the 'user experience' in the application I'm creating. While I know
I could allow the user to enter in number and alpha text - in a text box -
and then tell them when the execuate a command "This is not numeric data", I
would rather not allow them to enter alpha data - to begin with.
I've posted the below code from a page someone suggested. It is from a William Ryan. I have used it - it does work - but I run into two problems.
One, the user cannot use the backspace key and two, it allows someone to
enter another "." - decimal. The code author realizes this and says, "The
use above will allow all valid numbers as well as decimals. It wouldn't be
very difficult to expand upon this to verify that you don't have two decimal
in the number, allow for currency characters etc." However - to be quite
honest - I don't follow what the code is even doing. Can someone clarify
what it is doing and how one would modify it to allow for only one decimal?
(Bernie Yaeger I did read your post as well - if you could let me know how I
could download your code/control - I would love to see it) Please see
William's code below (link:
http://www.knowdotnet.com/articles/n...textboxes.html)
Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar)
Dim isDecimal As Boolean = e.KeyChar.ToString = "."
If Not isKey And Not isDecimal Then
e.Handled = True
End If
End Sub

Nov 20 '05 #2

P: n/a
* "=?Utf-8?B?S2VpdGg=?=" <an*******@discussions.microsoft.com> scripsit:
I've posted the below code from a page someone suggested. It is from
a William Ryan. I have used it - it does work - but I run into two
problems. One, the user cannot use the backspace key and two, it allows
someone to enter another "." - decimal.


There is a 3rd problem: It doesn't allow me to enter a number in German
number format when I run the app on a German language system (for
example, "12,3". And it prevents me from entering a number in hex or
octal format.

What if the user already entered a "." and now wants to move it to
another position inside the number he has typed into the textbox? By
forbidding the user to enter a 2nd ".", editing will be very hard. The
user will have to delete the ".", then move to another position and
enter the "." there.

Just my 2 Euro cents...

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>
Nov 20 '05 #3

P: n/a
Hi Keith,

When you was stayed in the original thread and told there what where the
problems, than I could have given you this sample I made already some days
ago. It includes the methode which Herfried wants as well, I think this one
is one of the nicest for the customer.

I hope this helps?

Cor

\\\
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.TextBox1.MaxLength = 10 'or whatever you want
End Sub
Private Sub textbox1_KeyUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) Handles textbox1.KeyUp
If e.KeyValue <> 8 Then
If Not IsNumeric(TextBox1.Text) Then
MessageBox.Show("Only numeric is allowed")
TextBox1.SelectionStart = TextBox1.Text.Length - 1
TextBox1.SelectionLength = 1
End If
End If
End Sub
Private Sub TextBox1_Validating(ByVal sender _
As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox1.Validating
If Not IsNumeric(TextBox1.Text) Then
MessageBox.Show("There was an error pasting")
TextBox1.Focus()
End If
End Sub
///

Nov 20 '05 #4

P: n/a
Try this Keith:

Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox3.KeyPress
If e.KeyChar.IsDigit(e.KeyChar) OrElse e.KeyChar = Chr(Keys.Back)
Then Exit Sub
If e.KeyChar.IsPunctuation(e.KeyChar) AndAlso
TextBox3.Text.IndexOf(".") = -1 Then Exit Sub
e.Handled = True

End Sub
"Keith" <an*******@discussions.microsoft.com> wrote in message
news:BA**********************************@microsof t.com...
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely
reading them all - but I think I have a differing opinion of how I want to
handle the 'user experience' in the application I'm creating. While I know
I could allow the user to enter in number and alpha text - in a text box -
and then tell them when the execuate a command "This is not numeric data", I
would rather not allow them to enter alpha data - to begin with.
I've posted the below code from a page someone suggested. It is from a William Ryan. I have used it - it does work - but I run into two problems.
One, the user cannot use the backspace key and two, it allows someone to
enter another "." - decimal. The code author realizes this and says, "The
use above will allow all valid numbers as well as decimals. It wouldn't be
very difficult to expand upon this to verify that you don't have two decimal
in the number, allow for currency characters etc." However - to be quite
honest - I don't follow what the code is even doing. Can someone clarify
what it is doing and how one would modify it to allow for only one decimal?
(Bernie Yaeger I did read your post as well - if you could let me know how I
could download your code/control - I would love to see it) Please see
William's code below (link:
http://www.knowdotnet.com/articles/n...textboxes.html)
Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar)
Dim isDecimal As Boolean = e.KeyChar.ToString = "."
If Not isKey And Not isDecimal Then
e.Handled = True
End If
End Sub

Nov 20 '05 #5

P: n/a
Oops, mistake. Now it will work

Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox3.KeyPress
If e.KeyChar.IsDigit(e.KeyChar) OrElse e.KeyChar = Chr(Keys.Back)
Then Exit Sub
If e.KeyChar = "."c AndAlso TextBox3.Text.IndexOf(".") = -1 Then
Exit Sub

e.Handled = True

End Sub


"yEaH rIgHt" <nospam@haha> wrote in message
news:10*************@corp.supernews.com...
Try this Keith:

Private Sub TextBox3_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox3.KeyPress
If e.KeyChar.IsDigit(e.KeyChar) OrElse e.KeyChar = Chr(Keys.Back)
Then Exit Sub
If e.KeyChar.IsPunctuation(e.KeyChar) AndAlso
TextBox3.Text.IndexOf(".") = -1 Then Exit Sub
e.Handled = True

End Sub
"Keith" <an*******@discussions.microsoft.com> wrote in message
news:BA**********************************@microsof t.com...
I apologize for those of you who think I'm posting on the same topic. It
is not that I don't appreciate all of your comments - and I'm definitely
reading them all - but I think I have a differing opinion of how I want to
handle the 'user experience' in the application I'm creating. While I know I could allow the user to enter in number and alpha text - in a text box -
and then tell them when the execuate a command "This is not numeric data", I would rather not allow them to enter alpha data - to begin with.

I've posted the below code from a page someone suggested. It is from a William Ryan. I have used it - it does work - but I run into two

problems. One, the user cannot use the backspace key and two, it allows someone to
enter another "." - decimal. The code author realizes this and says, "The
use above will allow all valid numbers as well as decimals. It wouldn't be very difficult to expand upon this to verify that you don't have two decimal in the number, allow for currency characters etc." However - to be quite
honest - I don't follow what the code is even doing. Can someone clarify
what it is doing and how one would modify it to allow for only one decimal? (Bernie Yaeger I did read your post as well - if you could let me know how I could download your code/control - I would love to see it) Please see
William's code below (link:
http://www.knowdotnet.com/articles/n...textboxes.html)

Private Overloads Sub TextBox1_TextChanged(ByVal sender As
System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles

TextBox1.KeyPress
Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar)
Dim isDecimal As Boolean = e.KeyChar.ToString = "."
If Not isKey And Not isDecimal Then
e.Handled = True
End If
End Sub


Nov 20 '05 #6

P: n/a
* "Cor Ligthert" <no**********@planet.nl> scripsit:
ago. It includes the methode which Herfried wants as well, I think this one
is one of the nicest for the customer. [...] If Not IsNumeric(TextBox1.Text) Then
MessageBox.Show("There was an error pasting")
TextBox1.Focus()


I do not like messageboxes. This will prevent the user from leaving the
control if he/she is not able to enter valid data.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>
Nov 20 '05 #7

P: n/a
Hi Herfreid,

I can't believe you're sticking to your position. First, you know very well
that you can program around the minor problems you mention. Second, if I
want you to fill out a form in black ink, I give you the form and a black
pen. If I give you a red pen as well and you use it, do I tell you at the
end that the form was to be filled out in black ink and ask you to fill it
out again?

Bernie

"Herfried K. Wagner [MVP]" <hi***************@gmx.at> wrote in message
news:el**************@tk2msftngp13.phx.gbl...
* "=?Utf-8?B?S2VpdGg=?=" <an*******@discussions.microsoft.com> scripsit:
I've posted the below code from a page someone suggested. It is from
a William Ryan. I have used it - it does work - but I run into two
problems. One, the user cannot use the backspace key and two, it allows
someone to enter another "." - decimal.


There is a 3rd problem: It doesn't allow me to enter a number in German
number format when I run the app on a German language system (for
example, "12,3". And it prevents me from entering a number in hex or
octal format.

What if the user already entered a "." and now wants to move it to
another position inside the number he has typed into the textbox? By
forbidding the user to enter a 2nd ".", editing will be very hard. The
user will have to delete the ".", then move to another position and
enter the "." there.

Just my 2 Euro cents...

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>

Nov 20 '05 #8

P: n/a
Hi Keith,

I became crazy from that Herfried (is not true), in the sample is a problem
when you set it to blank or would leave the program with an error. I changed
that.

Remember it is just a sample, how you do your error is your sake, you can
use by instance an errorprovider for that, but that would make the sample
less simple to show, while this one becomes already more and more difficult
to show

(statified with the text of the errroprovider now Herfried?)

Cor
\\\\
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Me.TextBox1.MaxLength = 10
End Sub
Private Sub textbox1_KeyUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyEventArgs) Handles textbox1.KeyUp
If e.KeyValue <> 8 Then
If Not IsNumeric(TextBox1.Text) Then
If TextBox1.Text.Length > 0 Then
MessageBox.Show("Only 1 to 10 is allowed")

TextBox1.SelectionStart = TextBox1.Text.Length - 1
TextBox1.SelectionLength = 1
End If

End If
End If
End Sub
Private Sub TextBox1_Validating(ByVal sender _
As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
Handles TextBox1.Validating
If TextBox1.Text.Length > 0 Then
If Not IsNumeric(TextBox1.Text) Then
MessageBox.Show("There was an error pasting")
TextBox1.Focus()
e.Cancel = True
End If
End If
End Sub
////
Nov 20 '05 #9

P: n/a
* "Bernie Yaeger" <be*****@cherwellinc.com> scripsit:
I can't believe you're sticking to your position. First, you know very well
that you can program around the minor problems you mention. Second, if I
want you to fill out a form in black ink, I give you the form and a black
pen. If I give you a red pen as well and you use it, do I tell you at the
end that the form was to be filled out in black ink and ask you to fill it
out again?


Paper forms are very different from forms on the computer. You can
provide context-sensitive help for the control and display information
about how to fill in the values there. In an application, we used an
errorprovider with an icon showing a "?" on a blue filled square that
displayed information on what to will in. If the input was not valid,
we showed an errorprovider.

I didn't say that there should not be any guidance at all. There should
be hints, and in some special cases custom controls make sense (for
example, DateTimePicker). But even this control has its problems and
limitations. What I like is if the control reformats the input after
successfully validating its contents, but even that can be annoying.

--
Herfried K. Wagner [MVP]
<URL:http://dotnet.mvps.org/>
Nov 20 '05 #10

P: n/a
Here is the approach that I used. This post is a little long but it is
complete.
This textbox checks the entered text upon the user leaving the textbox, this
allows the user to edit the text and have an incorrect value part way
through
the editing sequence without interupting the user. If the text is not
correct on
leaving the textbox the user is presented a messagebox with a message
(setable
as a property) explaining the problem and the correct entry format. Note
that
the user can enter nothing (i.e. "") and is able to exit the textbox. I
hate getting
stuck in a textbox on some form and can't get out. Always check for a nil
entry.

Let me first say that this is heavly plagerized from an article at the MS
site
about Regular Expressions. I initally created a smart text box control that
could validate itself. Create a control library and a SmartTextBox control
as follows.

Imports System.Text.RegularExpressions
Public Class SmartTextBox

Inherits System.Windows.Forms.TextBox

#Region " Windows Form Designer generated code "

Public Sub New()

MyBase.New()

'This call is required by the Windows Form Designer.

InitializeComponent()

'Add any initialization after the InitializeComponent() call

Me.ValidationExpression = ".*"

End Sub

'UserControl1 overrides dispose to clean up the component list.

Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose()

End If

End If

MyBase.Dispose(disposing)

End Sub

'Required by the Windows Form Designer

Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer

'It can be modified using the Windows Form Designer.

'Do not modify it using the code editor.

<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

End Sub

#End Region

' String representation of the RegEx that will be used to

' validate the text in the TextBox. This is needed because

' the property needs to be exposed as a string to be set

' at design time.

Protected validationPattern As String

' Message that should be available if the text does not

' match the pattern.

Protected mErrorMessage As String

' RegEx object that's used to perform the validation.

Protected mValidationExpression As Regex

' Default color to use if the text in the TextBox is not

' valid.

Protected mErrorColor As Color = Color.Red

' Allow the developer to set the error message

' at design time or run time.

Public Property ErrorMessage() As String

Get

Return mErrorMessage

End Get

Set(ByVal Value As String)

mErrorMessage = Value

End Set

End Property

' If the TextBox text does not match the RegEx, then it

' will be changed to this color.

Public Property ErrorColor() As Color

Get

Return mErrorColor

End Get

Set(ByVal Value As Color)

mErrorColor = Value

End Set

End Property

' Let's the developer determine if the text in the TextBox

' is valid.

Public ReadOnly Property IsValid() As Boolean

Get

If Not mValidationExpression Is Nothing Then

Return mValidationExpression.IsMatch(Me.Text)

Else

Return True

End If

End Get

End Property

' Lets the developer specify the regular expression (as

' a string) that will be used to validate the text in the

' TextBox. It's important that this be setable as a string

' (vs. a RegEx object) so that the developer can specify

' the RegEx pattern using the properties window.

Public Property ValidationExpression() As String

Get

Return validationPattern

End Get

Set(ByVal Value As String)

mValidationExpression = New Regex(Value)

validationPattern = Value

End Set

End Property

' If the text does not match the RegEx, then change the

' color of the text to the ErrorColor. If it does match

' then make sure it's displayed using the default color.

Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)

If Not Me.IsValid And Me.Text <> "" Then

Me.ForeColor = mErrorColor

Me.Focus()

MsgBox(mErrorMessage)

Else

Me.ForeColor = Me.DefaultForeColor

End If

' Any time you inherit a control, and override one of

' the On... subs, it's critical that you call the On...

' method of the base class, or the control won't fire

' events like it's supposed to.

MyBase.OnValidated(e)

End Sub

End Class

===========

Then I create a SmartDoubleTextBox that knows how to
check for a valid expression and then converts it into a
NumericValue that is available to the developer as a property
Public Class SmartDoubleTextBox

' The various validating textboxes all inherit RegExTextBox

' which can varify that the contents of any TextBox match

' a regular expression.

Inherits SmartTextBox

' TextBox's numeric value

Protected mNumericValue As Double

Protected mFormatString As String

#Region " Windows Form Designer generated code "

Public Sub New()

MyBase.New()

'This call is required by the Windows Form Designer.

InitializeComponent()

'Add any initialization after the InitializeComponent() call

Me.ValidationExpression = "^\-?\d{1,}\.?\d{0,}$"

Me.ErrorMessage = "This number must be in the form of 12.345 (+ or -)"

Me.mFormatString = "F2"

End Sub

'UserControl overrides dispose to clean up the component list.

Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose()

End If

End If

MyBase.Dispose(disposing)

End Sub

'Required by the Windows Form Designer

Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer

'It can be modified using the Windows Form Designer.

'Do not modify it using the code editor.

<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

components = New System.ComponentModel.Container()

End Sub

#End Region

Public Overridable Property NumericValue() As Double

Get

Return mNumericValue

End Get

Set(ByVal Value As Double)

mNumericValue = Value

Me.Text = Format(Value, mFormatString) '.ToString

End Set

End Property

Public Property FormatString() As String

Get

Return mFormatString

End Get

Set(ByVal Value As String)

mFormatString = Value

End Set

End Property

Protected Overrides Sub OnValidated(ByVal e As System.EventArgs)

If Me.IsValid Then

Me.mNumericValue = Convert.ToDouble(Me.Text)

Else

Me.mNumericValue = Nothing

Me.Invalidate()

End If

' Any time you inherit a control, and override one of

' the On... subs, it's critical that you call the On...

' method of the base class, or the control won't fire

' events like it's supposed to.

MyBase.OnValidated(e)

End Sub

End Class

===========

"Keith" <an*******@discussions.microsoft.com> wrote in message
news:BA**********************************@microsof t.com...
I apologize for those of you who think I'm posting on the same topic. It is not that I don't appreciate all of your comments - and I'm definitely
reading them all - but I think I have a differing opinion of how I want to
handle the 'user experience' in the application I'm creating. While I know
I could allow the user to enter in number and alpha text - in a text box -
and then tell them when the execuate a command "This is not numeric data", I
would rather not allow them to enter alpha data - to begin with.
I've posted the below code from a page someone suggested. It is from a William Ryan. I have used it - it does work - but I run into two problems.
One, the user cannot use the backspace key and two, it allows someone to
enter another "." - decimal. The code author realizes this and says, "The
use above will allow all valid numbers as well as decimals. It wouldn't be
very difficult to expand upon this to verify that you don't have two decimal
in the number, allow for currency characters etc." However - to be quite
honest - I don't follow what the code is even doing. Can someone clarify
what it is doing and how one would modify it to allow for only one decimal?
(Bernie Yaeger I did read your post as well - if you could let me know how I
could download your code/control - I would love to see it) Please see
William's code below (link:
http://www.knowdotnet.com/articles/n...textboxes.html)
Private Overloads Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim isKey As Boolean = e.KeyChar.IsDigit(e.KeyChar)
Dim isDecimal As Boolean = e.KeyChar.ToString = "."
If Not isKey And Not isDecimal Then
e.Handled = True
End If
End Sub

Nov 20 '05 #11

P: n/a
Following up on the above already too long post.

I then use these two controls as base classes for other controls. I use the
SmartTextBox as a base for non-numeric stuff like phone numbers, zip codes
and social security numbers. I use the SmartDoubleTextBox as a base for any
real numbers such as singles, integers and percentage.

You can either create another control for the function you want (my prefered
method) or just change the regular expression in the properties window at
design time.
"Earthlink" <ji******@mindspring.com> wrote in message
news:nw****************@newsread2.news.pas.earthli nk.net...
Here is the approach that I used. This post is a little long but it is
complete.
This textbox checks the entered text upon the user leaving the textbox, this allows the user to edit the text and have an incorrect value part way
through
the editing sequence without interupting the user. If the text is not
correct on
leaving the textbox the user is presented a messagebox with a message
(setable
as a property) explaining the problem and the correct entry format. Note
that
the user can enter nothing (i.e. "") and is able to exit the textbox. I
hate getting
stuck in a textbox on some form and can't get out. Always check for a nil
entry.

Let me first say that this is heavly plagerized from an article at the MS
site
about Regular Expressions. I initally created a smart text box control that could validate itself. Create a control library and a SmartTextBox control as follows.

Nov 20 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.