Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Numeric text box 2

Status
Not open for further replies.

Andrzejek

Programmer
Joined
Jan 10, 2006
Messages
8,576
Location
US

I looked all over the net, Google it and found a lot of examples, most of them worked only partially.

How can I make a text box to accept numbers only?
Example:

1234 or 12.34, but NOT 123.45.67
And allow BackSpace and Delete keys to correct mistakes?

In VB6 I used:
Code:
Private Sub txtTextBox_KeyPress(KeyAscii As Integer)

If (KeyAscii > 47 And KeyAscii < 58) Or KeyAscii = 8 Then
    [green]'Only numbers are entered - it is OK[/green]
Else
    KeyAscii = 0
End If

End Sub

And I found this in VB.NET, but is not complete:

Code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
      ByVal e As System.Windows.Forms.KeyPressEventArgs) _
      Handles TextBox1.KeyPress

  If Not Char.IsNumber(e.KeyChar) Then
      e.Handled = True
  End If

End Sub
This allows me to enter numbers only, but I can not use BackSpace or Delete keys, and can not use period.

Have fun.

---- Andy
 
Try this:

Code:
	Private OldText As String = String.Empty
	Private OldPosition As Integer = 0

	Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

		OldText = TextBox1.Text
		OldPosition = TextBox1.SelectionStart

	End Sub

	Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged

		Dim d As Double = 0
		If Not Double.TryParse(TextBox1.Text, d) Then
			TextBox1.Text = OldText
			TextBox1.SelectionStart = OldPosition
			TextBox1.SelectionLength = 0
		End If

	End Sub

Hope this helps.

[vampire][bat]
 

Works like a dream, thank you :-)

Trying to decipher your code.
What do I need to change to allow numbers only and NOT a period? i.e. 1234


Have fun.

---- Andy
 

I think I got it:
Code:
If Not [blue]Integer[/blue].TryParse(TextBox1.Text, d) Then

Have fun.

---- Andy
 
There is a problem with the code that I posted. You cannot delete the ONLY character in the TextBox.

This resolves that situation:

Code:
	Private OldText As String = String.Empty
	Private OldPosition As Integer = 0

	Private DefaultValueIsZero As Boolean = True
	Private SetDefault As Boolean = False

	Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown

		OldText = TextBox1.Text
		OldPosition = TextBox1.SelectionStart
		SetDefault = False
		If OldText.Length = 1 Then
			If (OldPosition = 1 AndAlso e.KeyCode = Keys.Back) OrElse (OldPosition = 0 AndAlso e.KeyCode = Keys.Delete) Then
				If DefaultValueIsZero Then
					OldText = "0"
					OldPosition = 1
					SetDefault = True
				Else
					OldText = ""
					OldPosition = 0
				End If
			End If
		End If

	End Sub

	Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged

		Dim d As Double = 0
		If Not Double.TryParse(TextBox1.Text, d) Then
			TextBox1.Text = OldText
			TextBox1.SelectionStart = OldPosition
			TextBox1.SelectionLength = 0
		End If

	End Sub

To use Integer, use Integer.TryParse as you found, and don't forget to change the data type of the ByRef parameter variable as in:

[tt]Dim d As Double = 0[/tt]

needs to become:

[tt]Dim d As Integer = 0[/tt]


Hope this helps.


[vampire][bat]
 
Well Done, earthandfire. Thank you for this. Star for you.

=======================================
People think it must be fun to be a super genius, but they don't realize how hard it is to put up with all the idiots in the world. (Calvin from Calvin And Hobbs)

Robert L. Johnson III
CCNA, CCDA, MCSA, CNA, Net+, A+, CHDP
VB.NET Programmer
 

When I used your new code, and try to delete the only 1 digit in a text box, it gave me 0 which I could not delete. So I changed:

OldText = "0"

to

OldText = ""

Also, I can not see any use for boolean SetDefault, so I got rid of it and it works fine. What do you have SetDefault for?

Have fun.

---- Andy
 
SetDefault, was left in by mistake, sorry. In an earlier draft I had an additional flag which determined whether or not to use a default value.

To enable removing the "0", simply change:

[tt]Private DefaultValueIsZero As Boolean = True[/tt]

to:

[tt]Private DefaultValueIsZero As Boolean = False[/tt]


If you created a Numeric TextBox UserControl, then SetDefault and DefaultValue properties would be beneficial. Since this is just changing the behaviour of an ordinary TextBox, I consolidated the functionality of those "properties" into a single variable DefaultValueIsZero and forgot to properly clean up before posting.

Hope this helps.


[vampire][bat]
 
I just noticed that this code allows for scientific notation.

You cannot directly type a value represented in scientific notation directly in to the text box, but if you 'try pretty hard', you can get it in there.

Type: 1 0 (left arrow) e

You will get: 1e0

If you don't want to allow scientific notation, you could modify a single line.

Code:
If Not Double.TryParse(TextBox1.Text[!] & "e0"[/!], d) Then

If you don't want to allow fractional numbers either...

Code:
If Not Double.TryParse(TextBox1.Text[!] & ".0e0"[/!], d) Then

You could easily say this is nit-picking, and I do apologize for that. From a 'user typing things in to a textbox perspective', this is very unlikely to happen. However, if a user copy/pastes in to the text box, it could happen.


-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 

Nice solutions, but a lot of code.

How about this:
Code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, _
  ByVal e As System.Windows.Forms.KeyPressEventArgs) _
  Handles TextBox1.KeyPress

[blue]If e.KeyChar = "." And _
    Strings.InStr(TextBox1.Text, ".") Then[/blue]
    [green]'Already have one period[/green]
[blue]    e.Handled = True
    Exit Sub
End If[/blue]

If Char.IsDigit(e.KeyChar) Or _
    (e.KeyChar) = vbBack [blue]Or _
    (e.KeyChar) = "." [/blue]Then
[green]    'It is OK, Numbers, BackSpace and Period allowed[/green]
Else
    e.Handled = True
End If

End Sub
Blue code is for period only.

I've been testing it and looks to me that it is working OK
I don't really care about Copy/Cut/Paste some weird data, just simple typing.

Does anybody see anything wrong with this appropach?

Have fun.

---- Andy
 
I know it's kinda lazy, but why not just use a masked textbox with 10-15 zeros for the mask and a space for the prompt char. No Code, No debugging and no funkiness to deal with...

-Sometimes the answer to your question is the hack that works
 
Please I need some help with using Numeric TexBox.

- I am reading my data from A Dataset and all my controls are BINDED to a Custom Numeric TextBox.

ISSUE - I am having a problem with deleting the value in the textbox. I can only change the text in the textbox, but i want to be able to accept nulls in textbox.

When I chnage the text to Null, it returns to the previous value.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top