在我的项目中,我将客户端名称设置为主键,如果我输入相同的值,我会得到异常,现在我想编写验证,即如果我重新输入主键值,那么我应该得到一条消息,如“数据已存在”,请帮我这样做,我用来插入值的代码是:
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtName.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Project Name!");
txtName.Focus();
return;
}
if (txtContactPerson.Text == string.Empty)
{
MessageBox.Show("Please enter a value to Description!");
txtContactPerson.Focus();
return;
}
SqlConnection con = Helper.getconnection();
con.Open();
string commandText = "InsertClient";
SqlCommand cmd = new SqlCommand(commandText, con);
cmd.Parameters.AddWithValue("@Name", txtName.Text);
cmd.Parameters.AddWithValue("@ContactPerson", txtContactPerson.Text);
cmd.CommandType = CommandType.StoredProcedure;
MessageBox.Show("Client details are inserted successfully");
txtName.Clear();
txtContactPerson.Clear();
object Name = cmd.ExecuteNonQuery();
con.Close();
BindData();
}