日期:2014-05-17  浏览次数:20722 次

C#的winform中控制TextBox中只能输入数字

C#的winform中控制TextBox中只能输入数字

?

private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

{

?? ?//阻止从键盘输入键

?? ?e.Handled = true;

?? ?if(e.KeyChar>='0' && e.KeyChar <='9')

?? ?{

?? ? ? ?e.Handled = false;

?? ?}

?

}

?

?

多条件的:

?

private void TxtUser_KeyPress(object sender, KeyPressEventArgs e)

?? ? ? ?{

?? ? ? ? ? ?//阻止从键盘输入键

?? ? ? ? ? e.Handled = true;

?

?? ? ? ? ? ?if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == (char)8))

?? ? ? ? ? ?{

?

?? ? ? ? ? ? ? ?if ((e.KeyChar == (char)8)) { e.Handled = false; return; }

?? ? ? ? ? ? ? ?else

?? ? ? ? ? ? ? ?{

?? ? ? ? ? ? ? ? ? ?int len = TxtUser.Text.Length;

?? ? ? ? ? ? ? ? ? ?if (len < 5)

?? ? ? ? ? ? ? ? ? ?{

?? ? ? ? ? ? ? ? ? ? ? ?if (len == 0 && e.KeyChar != '0')

?? ? ? ? ? ? ? ? ? ? ? ?{

?? ? ? ? ? ? ? ? ? ? ? ? ? ?e.Handled = false; return;

?? ? ? ? ? ? ? ? ? ? ? ?}

?? ? ? ? ? ? ? ? ? ? ? ?else if(len == 0)

?? ? ? ? ? ? ? ? ? ? ? ?{

?? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("编号不能以0开头!"); return;

?? ? ? ? ? ? ? ? ? ? ? ?}

?? ? ? ? ? ? ? ? ? ? ? ?e.Handled = false; return;

?? ? ? ? ? ? ? ? ? ?}

?? ? ? ? ? ? ? ? ? ?else

?? ? ? ? ? ? ? ? ? ?{

?? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("编号最多只能输入5位数字!");

?? ? ? ? ? ? ? ? ? ?}

?? ? ? ? ? ? ? ?}

?? ? ? ? ? ?}

?? ? ? ? ? ?else

?? ? ? ? ? ?{

?? ? ? ? ? ? ? ?MessageBox.Show("编号只能输入数字!");

?? ? ? ? ? ?}

?

?

?? ? ? ?}