让TextBox只允许输入数字的方法需要注意的一点:
(1)
(3)将Form的KeyPreview 改为:true 即可。
(4)如果想控制TextBox的内容长度可以使用: this.userIdText.MaxLength = 7;
(1)
private void userIdText_KeyPress(object sender, KeyPressEventArgs e) //只能输入数字和. 但不能输入小数 {
//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
e.Handled = true;
//小数点的处理。
if ((int)e.KeyChar == 46) //小数点
{
if (userIdText .Text.Length <= 0)
e.Handled = true; //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(userIdText.Text, out oldf);
b2 = float.TryParse(userIdText.Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
e.Handled = true;
else
e.Handled = false;
}
}
}
}(2)在designer文件里找到: this.userIdText.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.userIdText_KeyPress);(3)将Form的KeyPreview 改为:true 即可。
(4)如果想控制TextBox的内容长度可以使用: this.userIdText.MaxLength = 7;

本文详细介绍了如何通过编程实现让TextBox控件只允许用户输入数字,包括关键事件处理、小数点输入规则和限制内容长度的方法。
2786

被折叠的 条评论
为什么被折叠?



