need homework help for textbox validation.

cozmo

Member
Joined
Sep 28, 2012
Messages
7
Programming Experience
3-5
Hello all, this is my first post.

I'm taking VB.NET (that I'm enjoying, actually) and I have a project due in a few days and need some advice. For three days I've been trying to figure this out but not familiar enough with VB's syntax yet. I've read many examples and seen a few demonstrated on YouTube but have not been able to implement any with my code. The problem is that I get more than one decimal because I can't solve how to indicate that if there's more than one period. Maybe an "indexof" and "-1" operation? But I couldn't get that to work either and I'm out of ideas.

I need to validate a text box for:

  • numbers only
  • one decimal (can be anywhere in the field.)
  • a backspace

This is what I've tried:
...on key press do the following (roughly because I don't have my code to look at right now.)
VB.NET:
If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <=57) Or Asc(e.KeyChar) = 8 Or Asc(e.KeyChar) = 46 Then
     e.Handled = true
Else
     e.Handled = false
Endif


  • nested IF to check the textbox for char 46.
  • A masked text box. But this won't work because I can't get rid of the prompt character and the input I need to type doesn't really have a mask. The decimal can be anywhere in the text field, but only once.
  • I've tried a few other things but met with frustration.

Ok, any ideas?

Thank you.


-Alex
 
The NumericUpDown control is a textbox that only allow numeric input, it has a DecimalPlaces property also.
 
Input single decimal point in textbox

VB.NET:
	Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
		If Not Char.IsDigit(e.KeyChar) Then e.Handled = True 'allow digits only
		If e.KeyChar = Chr(8) Then e.Handled = False 'allow Backspace
		If e.KeyChar = "-" And TextBox1.SelectionStart = 0 Then e.Handled = False 'allow negative number
		If e.KeyChar = "." And TextBox1.Text.IndexOf(".") = -1 Then e.Handled = False 'allow single decimal point
		If e.KeyChar = Chr(13) Then GetNextControl(TextBox2, True).Focus() 'Enter key moves to next control
	End Sub
 
Back
Top