Skip to content

Instantly share code, notes, and snippets.

@meng-hui
Created August 10, 2012 06:03
Show Gist options
  • Save meng-hui/3311578 to your computer and use it in GitHub Desktop.
Save meng-hui/3311578 to your computer and use it in GitHub Desktop.
Allow only numeric input in a windows form control
public static void AllowOnlyNumericInput (object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
//only allow one decimal point
if (e.KeyChar == '.' && (sender as System.Windows.Forms.TextBox).Text.IndexOf('.') > -1)
{
e.Handled = true;
}
//only allow one negative sign
if (e.KeyChar == '-')
{
e.Handled = true;
if (!(sender as System.Windows.Forms.TextBox).Text.Equals(String.Empty))
(sender as System.Windows.Forms.TextBox).Text = (-1 * double.Parse((sender as System.Windows.Forms.TextBox).Text)).ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment