Usage : On KeyPress Event we Can call the function to Validate the Text Box.
ChkDecimalNumbers(txtNo,e,2,3)
Parameter : Textbox , KeyPressEventArgs , Number of Digits before Decimal & Number of Digits After Decimal
Output :22.987
Asc(x.KeyChar) = 8 : It Represent BackSpace
Code :
Shared Sub ChkDecimalNumbers(ByVal ctxt As TextBox, ByVal x As System.Windows.Forms.KeyPressEventArgs, ByVal bfrDec As Int16, ByVal aftDec As Int16)
If (Char.IsControl(x.KeyChar) Or Char.IsDigit(x.KeyChar) = True) Or x.KeyChar = "." Or Asc(x.KeyChar) = 8 Then
If ctxt.Text.IndexOf(".") <> -1 Then
If x.KeyChar = "." Then
x.Handled = True
End If
If ctxt.SelectionStart >= 0 And Asc(x.KeyChar) <> 8 Then
If (((Mid(ctxt.Text, ctxt.Text.IndexOf(".") + 1).Length > aftDec And ctxt.SelectionStart > ctxt.Text.IndexOf(".")) Or (Mid(ctxt.Text, 1, ctxt.Text.IndexOf(".") + 1).Length > bfrDec And ctxt.SelectionStart < selectionlength = 0))) Then
x.Handled = True
End If
End If
Else
If (aftDec = 0 And x.KeyChar = ".") Or (((Mid(ctxt.Text, 1).Length > bfrDec - 1 And x.KeyChar <> "." And Asc(x.KeyChar) <> 8) Or (ctxt.SelectionStart > bfrDec And x.KeyChar.ToString.Equals("."))) And ctxt.SelectionLength = 0) Then
x.Handled = True
End If
End If
Else
x.Handled = True
End If
End Sub