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

时间:2022-09-06 11:45:47

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("编号只能输入数字!");

}

}

 

//控制智能输入小数

private string perText;
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
var text = textBox1.Text;
double result;
Double.TryParse(textBox1.Text, out result);

if (result != 0)
{
perText = text;
}
else
{
textBox1.Text = perText;
this.textBox1.SelectionStart = this.textBox1.Text.Length;
this.textBox1.Focus();
}
}