WinForm 中限制只能输入数字
在Winform(C#)中要实现限制Textbox只能输入数字,一般的做法就是在按键事件中处理,判断keychar的值。限制只能输入数字,小数点,Backspace,del这几个键。数字0~9所对应的keychar为48~57,小数点是46,Backspace是8。
拖一个Textbox到窗体上,添加OnKeyPress事件,在事件写判断的代码,只要判断不是这些键,设置e.Handled的值为true,就可以屏蔽输入。
方法一:
private void tBox_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 0x20) e.KeyChar = (char)0; //禁止空格键 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+$"; string content = ((TextBox)sender).Text; if (!(Regex.IsMatch(content, pattern))) { errorProvider1.SetError((Control)sender, "只能输入数字!"); e.Cancel = true; } else errorProvider1.SetError((Control)sender, null); }
方法五:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { if(e.KeyChar=='.' && this.textBox1.Text.IndexOf(".")!=-1) { e.Handled=true; } if(!((e.KeyChar>=48 && e.KeyChar<=57) || e.KeyChar=='.' || e.KeyChar==8)) { e.Handled=true; } }
方法六:
private void tbx_LsRegCapital_KeyPress(object sender, KeyPressEventArgs e) { if (!Char.IsNumber(e.KeyChar) && !Char.IsPunctuation(e.KeyChar) && !Char.IsControl(e.KeyChar)) { e.Handled = true;//消除不合适字符 } else if (Char.IsPunctuation(e.KeyChar)) { if (e.KeyChar != '.' || this.textBox1.Text.Length == 0)//小数点 { e.Handled = true; } if (textBox1.Text.LastIndexOf('.') != -1) { e.Handled = true; } } }
方法七:
利用ASCII码处理办法、
{
if ((e.KeyChar <= 48 || e.KeyChar >=57) && (e.KeyChar != 8) && (e.KeyChar != 46))
e.Handled = true;
================48代表0,57代表9,8代表空格,46代表小数点
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构