C#项目中接触了TextBox只允许输入数字的问题,这倒不难,如下:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; //允许输入数字 if(e.KeyChar==(char)8) //允许输入回退键 { e.Handled=false; } } 但是如果要输入小数点,做成象计算器的那样,可真难了我几天,网上搜索了半天也没答案, 还是自己写吧,效果不错(高手不要笑我,没什么难度,只是自己的一点小经验), 有兴趣的朋友可以看看: private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { string str=this.textBox1.Text; e.Handled = e.KeyChar < '0' || e.KeyChar > '9'; //允许输入数字 if(e.KeyChar==(char)8) //允许输入回退键 { e.Handled=false; } if(e.KeyChar==(char)46) { if(str=="") //第一个不允许输入小数点 { e.Handled=true; return; } else { //小数点不允许出现2次 foreach(char ch in str) { if(char.IsPunctuation(ch)) { e.Handled=true; return; } } e.Handled=false; } } } |
C#中TextBox只允许输入数字或小数
最新推荐文章于 2025-04-16 19:50:15 发布