Winform TextBox中只能输入数字的几种常用方法(C#)
1个回答
展开全部
if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return; //处理负数
if (e.KeyChar 0x20){try{double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());}catch{
e.KeyChar = (char)0; //处理非法字符}}}方法二:private void TextBox_KeyPress(object sender, KeyPressEventArgs e){if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar)){
e.Handled = true;}}或者private void TextBox_KeyPress(object sender, KeyPressEventArgs e){if(e.KeyChar!='\b'&&!Char.IsDigit(e.KeyChar)){
e.Handled = true;}}方法三:private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e){if(e.KeyChar!='\b')//这是允许输入退格键{if((e.KeyChar<'0')||(e.KeyChar'9'))//这是允许输入0-9数字{
e.Handled = true;}}}方法四:private void textBox1_Validating(object sender, CancelEventArgs e){const string pattern = @"^\d+\.?\d+$";
if (e.KeyChar 0x20){try{double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());}catch{
e.KeyChar = (char)0; //处理非法字符}}}方法二:private void TextBox_KeyPress(object sender, KeyPressEventArgs e){if(e.KeyChar!=8&&!Char.IsDigit(e.KeyChar)){
e.Handled = true;}}或者private void TextBox_KeyPress(object sender, KeyPressEventArgs e){if(e.KeyChar!='\b'&&!Char.IsDigit(e.KeyChar)){
e.Handled = true;}}方法三:private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e){if(e.KeyChar!='\b')//这是允许输入退格键{if((e.KeyChar<'0')||(e.KeyChar'9'))//这是允许输入0-9数字{
e.Handled = true;}}}方法四:private void textBox1_Validating(object sender, CancelEventArgs e){const string pattern = @"^\d+\.?\d+$";
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询