Follow these steps:
- Generate KeyPress event for textbox by going into properties>>event, and then double click in front of KeyPress. Event will be automatically generated
- Now write this code in generated event:
if(!(char.IsDigit(e.KeyChar)))
e.Handled=true;
e.KeyChar is character corresponding to key pressed
char.IsDigit( ) is a function whose return value is bool, it accepts one character and if character is digit it returns true otherwise false
e.Handled sets the value indicating whether a event is handled or not
e.Handled=true; means this event is handled i.e. the pressed key will be disabled, so the the character will not be shown in text-box
Note: If you are using above code only digits are allowed, you cannot use backspace as all other keys are handled i.e. disabled. For avoiding this use the following code instead of above code:
if (!(char.IsDigit(e.KeyChar)||e.KeyChar ==(char )Keys.Back ))
e.Handled = true;
Now if key pressed is digit or backspace it will not be handled i.e. disable otherwise it will be handle
No comments:
Post a Comment