关键代码:
class="csharpcode"> /// <summary> /// 只能输入数字【KeyPress事件】 /// </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> /// 只能输入正浮点型数字【KeyPress事件】 /// </summary> /// <param name="textBox">TextBox</param> /// <param name="e">KeyPressEventArgs</param> public static void OnlyInputFloat(this TextBox textBox, KeyPressEventArgs e) { TextBox _curTextBox = textBox; if (e.KeyChar == 46) { if (_curTextBox.Text.Length <= 0) { e.Handled = true; } else { string _txtValue = _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; } } } }
代码使用:
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); }希望有所帮助!