Recent site activity

Tutorials‎ > ‎C# Tutorials‎ > ‎

Restrict textbox to numeric only

posted Nov 23, 2010 7:32 AM by Tim Key   [ updated Nov 26, 2010 6:21 AM ]
Instructions:  Place the code below into a KeyPress event for the textbox you wish to restrict


Code Snippet:

//The first "if" statement is for numeric only.  The second section "else if" allows one decimal place.

//You may leave off the "else if" if you do not wish to allow a decimal.

if (char.IsNumber(e.KeyChar) || char.IsControl(e.KeyChar))
{
    //Allow
}
else if (e.KeyChar == Convert.ToChar(".") && textbox1.Text.IndexOf(".") == -1)
{
    //Allow
}
else
{
    e.Handled = true;
}