Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to make a text box use only numbers and not letters?
Posted
Comments
PrashantSonewane 17-Apr-13 6:45am    
What kind of application? Windows or Web? Try using regex and let us know if have any issue.

Try this:
C#
void NumberValidation(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 48 && e.KeyChar <= 57))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }
 
Share this answer
 
Comments
Monster Maker 17-Apr-13 6:50am    
what about backspace??
You didn't try Google, did you?
Have a look, for instance, at this Stack Overflow question: "How do I make a textbox that only accepts numbers?"[^].
 
Share this answer
 
Comments
Johnny J. 17-Apr-13 9:08am    
CP, Why are you directing him to Stack Overflow when there are at least 20 articles about it here on "our site"??? :-)
CPallini 17-Apr-13 12:58pm    
:-)
if Windows Application : In the textbox event :

C#
private void txtZip_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}



if Web application :

XML
<head  runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        function CheckNumeric(e) {

            if (window.event) // IE
            {
                if ((e.keyCode < 48 || e.keyCode > 57) & e.keyCode != 8) {
                    event.returnValue = false;
                    return false;

                }
            }
            else { // Fire Fox
                if ((e.which < 48 || e.which > 57) & e.which != 8) {
                    e.preventDefault();
                    return false;

                }
            }
        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:textbox id="TextBox1" runat="server" onkeypress="CheckNumeric(event);"
             xmlns:asp="#unknown"></asp:textbox>
    </form>
</body></head>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900