而不是抛出一个错误,当他们进入不正确的输入类型的用户,进入任何东西,但数字开始与阻止他们。
事件
在文本框使用一个按键事件,像这样:
private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
// Get reference to calling control
TextBox textBox = sender as TextBox;
// Only allow 0-9, ., -
if (!char.IsControl(e.KeyChar) &&
!char.IsDigit(e.KeyChar) &&
e.KeyChar != '-' &&
e.KeyChar != '.')
{
e.Handled = true;
}
// Avoid double decimals
if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1)
{
e.Handled = true;
}
// Ensure hyphen is at the beginning
if (e.KeyChar == '-' &&
(textBox.Text.Contains('-') ||
textBox.SelectionStart != 0))
{
e.Handled = true;
}
}
这将只允许数值,小数,并且要输入连字符。此外,这还会阻止输入中的1位十进制.
,并确保用户只能在文本的开头输入连字符-
。
注册事件处理
注册此事件处理程序只需添加这行代码到你的构造函数形式。
// Be sure to change yourtextcontrol to the appropriate name.
yourtextcontrol.KeyPress += new KeyPressEventHandler(textBox_KeyPress);
验证输入
您还应该使用TryParse
在点击事件要仔细检查的条目。
private void buttonMul_Click(object sender, KeyPressEventArgs e)
{
if (double.TryParse(textOperand1.Text, out Operand1) &&
double.TryParse(textOperand2.Text, out Operand2))
{
result = Operand1 * Operand2;
textresult.Text = result.ToString();
}
else
{
// Error here. You can use a messagebox or whatever suits you.
}
}
看看'Double.TryParse'方法 – dcg
您可以使用try和catch块,并创建消息在catch块弹出框。这将显示的是try块不起作用。或者你可以使用Double.TryParse()方法。 –
我建议你防止用户在第一个地方输入无效输入,而不是让他们输入无效输入,然后在它们上面播放“gotcha”类型的错误消息。 –