private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
//允许输入数字、小数点、删除键和负号
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('-') && e.KeyChar != 13)
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
if (e.KeyChar == (char)('-'))
{
if (textBox1.Text != "")
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
textBox1.Text = 0.ToString();
int number = Convert.ToInt32(this.textBox1.Text);
textBox1.Text = number.ToString();
if (number <= 48 && number >= -110)
{
return;
}
MessageBox.Show("只能输入数字且大于-110小于48", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
报错信息:
if (e.KeyChar == (char)('-'))
{
if (textBox1.Text != "")
{
MessageBox.Show("请输入正确的数字");
this.textBox1.Text = "";
e.Handled = true;
}
}
我在网上查了,换了TextChanged事件里面的代码,运用try-catch可以运行负号,并且也能够达到不超过范围的要求,问题已解决,谢谢