當我嘗試一個沒有字符的正則表達式時,我的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
}
您應該*只*使用'驗證'事件進行輸入驗證,沒有別的。這是執行驗證的唯一正確時間點。 'Click'是錯誤的。另外,用'string.Empty'進行平等測試是多餘的,即使不是,也不要使用'string.Empty',使用'「」' - 它更短,*至少*可讀。畢竟,你不使用'int.Zero'。 – 2012-07-28 11:45:35