.net(c#) winform文本框只能输入数字,不能其他非法字符

时间:2022-12-23 17:49:32
 private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
//阻止从键盘输入键
e.Handled = true;
if(e.KeyChar>='' && e.KeyChar <='')
{
e.Handled = false;
} }
或者
private void tbID_KeyPress(object sender, KeyPressEventArgs e)
{
if (!((e.KeyChar >= '' && e.KeyChar <= '') || e.KeyChar == ' '))//不输入输入除了数字之外的所有非法字符的判断
{
e.Handled = true;
}
} 多条件的: private void TxtUser_KeyPress(object sender, KeyPressEventArgs e)
{
//阻止从键盘输入键
e.Handled = true; if ((e.KeyChar >= '' && e.KeyChar <= '') || (e.KeyChar == (char)))
{ if ((e.KeyChar == (char))) { e.Handled = false; return; }
else
{
int len = TxtUser.Text.Length;
if (len < )
{
if (len == && e.KeyChar != '')
{
e.Handled = false; return;
}
else if(len == )
{
MessageBox.Show("编号不能以0开头!"); return;
}
e.Handled = false; return;
}
else
{
MessageBox.Show("编号最多只能输入5位数字!");
}
}
}
else
{
MessageBox.Show("编号只能输入数字!");
} }