HOME

Thursday, October 20, 2016

On Key press event code, of Textbox to Accept digits only

1. drag a text box over the form
2. double click the textbox And change the event to key press event
3. right the following code in the key press event

 If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
            e.Handled = vbTrue
            MessageBox.Show("Enter digits only", "character press instead of number")
            TextBox1.Text = ""
            TextBox.Focus()
        End If
 
4. debug and try pressing character. it won't accept. it will accept only numbers


Explanation :

The "Char.IsDigit(e.KeyChar) = False " is the first condition That is been checked to verify what the
user's pressed if the user press a character (i.e not Digit)   then it will go for the second condition

"Char.IsControl(e.KeyChar) = False" this check's if what the user's pressed is control or not (i.e backspace, enter key e.t.c)

when this both conditions are satisfied then the condition becomes true , that the user pressed a character not a digit, number and not a control

the message box will be displayed to the user that the TextBox accepts digits only.
and then what ever is written in the textbox will be cleared and focus() will be return to the TextBox again.


Thank you

you can ask for more explanation if you felt to.

No comments:

Post a Comment