让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;