This code will allow the user to enter digits, '-' symbol(For negative value) and '.'(for decimal) only in the textbox
Private Sub expenseTextboxKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles expenseTextBox.KeyPress, revenueTextBox.KeyPress
'Handles for multiple textboxes
Dim tb As TextBox = CType(sender, TextBox) Dim chr As Char = e.KeyChar
If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then 'If adding the character to the end of the current TextBox value results in ' a numeric value, go on. Otherwise, set e.Handled to True, and don't let ' the character to be added. e.Handled = Not IsNumeric(tb.Text & e.KeyChar)
ElseIf e.KeyChar = "." Then 'For the decimal character (.) we need a different rule: 'If adding a decimal to the end of the current value of the TextBox results ' in a numeric value, it can be added. If not, this means we already have a ' decimal in the TextBox value, so we only allow the new decimal to sit in ' when it is overwriting the previous decimal. If Not (tb.SelectedText = "." Or IsNumeric(tb.Text & e.KeyChar)) Then e.Handled = True End If
ElseIf e.KeyChar = "-" Then 'A negative sign is prevented if the "-" key is pressed in any location ' other than the begining of the number, or if the number already has a ' negative sign If tb.SelectionStart <> 0 Or Microsoft.VisualBasic.Left(tb.Text, 1) = "-" Then e.Handled = True End If
ElseIf Not Char.IsControl(e.KeyChar) Then 'IsControl is checked, because without that, keys like BackSpace couldn't ' work correctly. e.Handled = True End If End Sub
|
| Author: harjit 01 Oct 2009 | Member Level: Bronze Points : 2 |
Public Function testForNumeric(ByRef value As String) As Boolean Dim allowedChars As String = "0123456789" For i As Integer = value.Length - 1 To 0 Step -1 If allowedChars.IndexOf(value(i)) = -1 Then Return False End If Next Return True End Function
|
| Author: Viji RAJKUMAR 02 Oct 2009 | Member Level: Diamond Points : 2 |
Harjit,
My code does not describe whether the string contains a numeric digit or not.
It prevents the user from entering non numeric characters (except one .(for decimal) and one - symbol (For negative number)) in the text box
You can post your code in the code snippets. Your code does not make any sense to me.
|