[WinForm] TextBox can only contain numbers or floating-point numbers.
Key code:
/// <Summary> /// you can only enter a number for the KeyPress event. /// </summary> /// <param name = "textBox"> TextBox </param>/ // <param name = "e"> KeyPressEventArgs </param> public static void OnlyInputNumber (this TextBox textBox, keyPressEventArgs e) {if (e. keyChar! = 8 &&! Char. isDigit (e. keyChar) {e. handled = true ;}} /// <summary> /// you can only enter a Positive floating point number [KeyPress event] /// </summary> /// <param name = "textBox"> TextBox </param >/// <param name = "e"> KeyPressEventArgs </param> public static void OnlyInputFloat (this TextBox textBox TextBox, keyPressEventArgs e) {TextBox _ curTextBox = textBox; if (e. keyChar = 46) {if (_ curTextBox. text. length <= 0) {e. handled = true;} else {string _ txtV Alue = _ curTextBox. text. trim (); float _ newValue, _ oldValue; bool _ oldResult = false, _ newResult = false; _ oldResult = float. tryParse (_ txtValue, out _ oldValue); _ newResult = float. tryParse (_ txtValue + e. keyChar. toString (), out _ newValue); if (! _ NewResult) {if (_ oldResult) e. Handled = true; else e. Handled = false ;}}}}
Code usage:
private void txtNumber_KeyPress(object sender, KeyPressEventArgs e) { TextBox _curTextBox = sender as TextBox; _curTextBox.OnlyInputNumber(e); } private void txtPrice_KeyPress(object sender, KeyPressEventArgs e) { TextBox _curTextBox = sender as TextBox; _curTextBox.OnlyInputFloat(e); }
Hope this is helpful!
In C # winform, how does one enable TEXTBOX to only input numbers and support Ctrl + V pasting?
Keypress does not support key combination. Ctrl + V is the key combination. Put the code in the keydown or keyup, and allow the ctrl + v combination key to pass through.
In winform of C #, how does one control that only numbers can be input in TextBox, including 0?
This is an integer verification implemented using a regular expression, but it is best to verify it in the submitted button event when you use it,
Public static bool IsIntNum (string str, bool msg)
{
System. Text. RegularExpressions. Regex reg1
= New System. Text. RegularExpressions.
Regex (@ "^ [-]? [1-9] {1} \ d * $ | ^ [0] {1} $ ");
Bool ismatch = reg1.IsMatch (str );
If (! Ismatch)
MessageBox. Show ("the number you entered is not an integer! "," Operation prompt ", MessageBoxButtons. OK, MessageBoxIcon. Information );
Return ismatch;
}
Note: The MessageBox object is called here. You must reference Windows. form when referencing it.