Created
August 10, 2012 06:03
-
-
Save meng-hui/3311578 to your computer and use it in GitHub Desktop.
Allow only numeric input in a windows form control
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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