Monday, 23 June 2014

C# NET How to use only numeric value in a textbox

This is very simple way to use only numeric value in a textbox. For this purpose we have to use Keypress Event. By default we will get TextChanged Event. To get the KeyPress Event, single click on the textbox to focus it. Now go to properties window and click on the Bolt icon. Bolt icon will be on the top right corner of the properties window.

 KeyPress Event :

Now we will check if the pressed key isnumeric or not. The code will something be like this
if (!char.IsNumber(e.KeyChar) )

If the pressed key is not numeric character, it should not be appear in the textbox. To do so we have to handle the Backspace key. Actually the character will appear in the textbox and we will fire a code to delete the last typed character. To delete the last character we have to handle backspace key. Here is the code

e.Handled = e.KeyChar != (char)Keys.Back;


Here is the complete code : 


if (char.IsNumber(e.KeyChar))
            {
                return;
            }
            else
            {
                e.Handled = e.KeyChar != (char)Keys.Back;
            }


If you want to allow fraction value, you should allow a dot (.) also. To do so you can use the code below.

if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
            {
                return;
            }
            else
            {
                e.Handled = e.KeyChar != (char)Keys.Back;

            }


One more thing. You may noticed that we used e.KeyChar == '.' instead of e.KeyChar == "."
"." used to set a string value. But we are checking a character, not comparing nor setting a sting value. So we will use '.'

To watch this on youtube :
https://www.youtube.com/watch?v=T1fIKGBmBGc

No comments:

Post a Comment