我想在无效验证后停止插入数据库。就像下面的代码片段显示了无效电话号码的消息,但它仍然将代码插入到数据库中。还有一个问题,我想在我认为有这个潜在错误的整个程序上应用这个规则。
private void button1_Click(object sender, EventArgs e)
{
Regex regexObj = new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
if (regexObj.IsMatch(textBox3.Text))
{
string formattedPhoneNumber =
regexObj.Replace(textBox3.Text, "($1) $2-$3");
}
else
{
MessageBox.Show("Invalid Phone Number! \nFormat is (XXX) XXX-XXXX");
}
if (string.IsNullOrEmpty(textBox1.Text) || textBox1.Text.Trim().Length == 0)
{
MessageBox.Show("Field can't be left blank!");
return;
}
if (string.IsNullOrEmpty(textBox2.Text) || textBox2.Text.Trim().Length == 0)
{
MessageBox.Show("No Name for the Author!");
return;
}
SqlConnection con = new SqlConnection("Server = DAFFODILS-PC\\SQLEXPRESS;Database=Library;Trusted_Connection=True;");
SqlCommand sql1 = new SqlCommand("INSERT into Members VALUES('" + textBox1.Text + "' , '" + textBox2.Text + "','" + textBox3.Text + "')", con);
con.Open();
sql1.ExecuteNonQuery();
con.Close();
this.membersTableAdapter.Fill(this.booksDataSet.Members);
MessageBox.Show("Data Added!");
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox1.Focus();
}
}
我想,我必须为此使用一种方法,但我不知道如何。有什么建议么?