if语句后的输入验证
当我尝试一个没有字符的正则表达式时,我的winforms EnterValue在if语句后仍然被触发,我怎么能在触发器之后停止它呢?从方法if语句后的输入验证
private void EnterValue_Click(object sender, EventArgs e)
{
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, @"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
}
//convert input to double
listDouble.Add(Convert.ToDouble(textBox1.Text)); // this line still throws exception
textBox1.Clear();
//clear existing items
listBox1.Items.Clear();
// clear any existing list items
for (int i = 0; i < listDouble.Count; i++)
{
listBox1.Items.Add(listDouble[i]);
}
//for each value added, add this to our list
}
返回:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, @"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return; // nothing after this will execute
}
如果if
谓词是真,这将只执行,并且该方法将尽快return;
语句已被打回,没有任何其他的代码正在运行。
第一种选择是使用return
:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, @"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return; // exit method
}
第二个选择是使用else
:
if (textBox1.Text != string.Empty && !Regex.IsMatch(textBox1.Text, @"^[0-9]+$"))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
}
else
{
// your statements
}
使用Decimal.TryParse
。并使用return
从目前的方法进行校验条件退出后:
的
return
声明终止于它出现的控制权返回给调用方法的方法的执行。
Decimal dec;
if (!Decimal.TryParse(textBox1.Text, out dec))
{
MessageBox.Show("Please only enter numbers");
textBox1.Clear();
return;
}
双打呢? – 2012-07-28 11:49:48
@JungleBoogie:我将'int'改为'Decimal'。 – Ria 2012-07-28 11:50:59
你应该事先测试。 – 2012-07-28 11:51:29
您应该*只*使用'验证'事件进行输入验证,没有别的。这是执行验证的唯一正确时间点。 'Click'是错误的。另外,用'string.Empty'进行平等测试是多余的,即使不是,也不要使用'string.Empty',使用'“”' - 它更短,*至少*可读。毕竟,你不使用'int.Zero'。 – 2012-07-28 11:45:35