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 
    } 
+0

您应该*只*使用'验证'事件进行输入验证,没有别的。这是执行验证的唯一正确时间点。 'Click'是错误的。另外,用'string.Empty'进行平等测试是多余的,即使不是,也不要使用'string.Empty',使用'“”' - 它更短,*至少*可读。毕竟,你不使用'int.Zero'。 – 2012-07-28 11:45:35

返回:

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 
    } 
+1

我更喜欢第一种方法,因为它减少了其他代码的缩进级别。 – Oded 2012-07-28 11:41:05

+0

我同意,我个人会使用'return'。我想表明,这也可以使用'if else else {}'语句完成。 – Zbigniew 2012-07-28 11:43:10

+0

我过去比较喜欢'return'方法,但现在不行了。如果你返回,那么很难看到函数的其他部分有时只会执行。 return语句的工作原理与goto语句几乎相同,并且隐藏了代码流。 – alaeus 2012-07-28 17:24:32

使用Decimal.TryParse。并使用return从目前的方法进行校验条件退出后:

return声明终止于它出现的控制权返回给调用方法的方法的执行。

Decimal dec; 
if (!Decimal.TryParse(textBox1.Text, out dec)) 
{ 
    MessageBox.Show("Please only enter numbers"); 
    textBox1.Clear(); 
    return; 
} 
+0

双打呢? – 2012-07-28 11:49:48

+0

@JungleBoogie:我将'int'改为'Decimal'。 – Ria 2012-07-28 11:50:59

+0

你应该事先测试。 – 2012-07-28 11:51:29