Social Icons

Pages

Tuesday, October 11, 2011

Numeric validation

Here's a small method for validating numeric in C#. It may save you some time.
public static bool DecimalInputValidation(TextBox textBox, KeyPressEventArgs e)
{
try
            {
                if (e.KeyChar == (char)8 || e.KeyChar == (char)46)
                {
                    e.Handled = false;
                    return true;
                }
                if (e.KeyChar >= (char)48 && e.KeyChar <= (char)57)
                {
                      string val = textBox.Text;
                    val = val + e.KeyChar.ToString();
                    decimal intVal = 0;
                    bool con = decimal.TryParse(val, out intVal);
                    if (con)
                    {
                        e.Handled = false;
                        return true;
                    }
                    else
                    {
                        e.Handled = true;
                        return false;
                    }
                }
                e.Handled = true;
                return false;
             }
            catch (Exception exp)
            {
                throw exp;
            }
}

No comments:

Post a Comment