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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Textbox Entry with Decimal Point 1

Status
Not open for further replies.

BBousman

Programmer
May 10, 2004
57
US
I'm trying to write a piece of code whereby the user who enters a numeric number in a field can only enter 2 numbers to the right of the decimal point and as many as they want to the left. Right now I can get it so it will only allow 2 numbers to the right but it doesn't allow me to put any numbers on the left of the decimal point unless you delete the decimal point first, does anyone know how to solve this one? Here's the code I have so far:

Private Function NumbersOnly(ByVal pstrChar As Char, ByVal oTextBox As TextBox) As Boolean

'validate the entry for a textbox limiting it to only numeric values and the decimal point

'accept only one instance of the decimal point
If (Convert.ToString(pstrChar) = "." And InStr(oTextBox.Text, ".")) Then Return True
If Convert.ToString(pstrChar) <> "." And pstrChar <> vbBack Then
If InStr(oTextBox.Text, ".") = 0 Or Len(Mid(oTextBox.Text, InStr(oTextBox.Text, ".") + 1, 3)) < 2 Then
Return IIf(IsNumeric(pstrChar), False, True) 'check if numeric is returned
Else
Return True
End If
End If
Return False 'for backspace

End Function
 
This should do what you want:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If TextBox1.Text.IndexOf(".") > 0 Then
If TextBox1.Text.Length - TextBox1.Text.IndexOf(".") = 3 Then
e.Handled = True
End If
End If
End Sub

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Oops, I left out the bit of code that makes this actually work:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If TextBox1.Text.IndexOf(".") > 0 Then
If TextBox1.SelectionStart > TextBox1.Text.IndexOf(".") Then
If TextBox1.Text.Length - TextBox1.Text.IndexOf(".") = 3 Then
e.Handled = True
End If
End If
End If
End Sub

There, now it works properly.


I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Just what I was looking for jebenson! Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top