本文介绍了如何避免通过winform将重复值输入表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中我已将客户端名称设置为主键,如果我输入相同的值,我将获得异常,现在我想编写验证,即如果我重新输入主键值,那么我应该得到一个像数据已存在这样的消息,请帮我这样做,我用来插入值的代码是:

in my project I have set the client name as primary key and if I enter the same value, I will get exception, now I want to write the validation, i.e if I re enter the primary key value then I should get a message like "Data already exists", Please help me to do that, The code I am using to insert value is:

  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();
}

推荐答案

try
{
    object Name = cmd.ExecuteNonQuery();
}
catch(SqlException sqlex)
{
    if(sqlex.Number == 2601 || sqlex.Number == 2627)
    {
        MessageBox.Show("Client Name already exists!");
        txtContactPerson.Focus();
    }
}
finally
{
    if(con!= null)
    {
       con.Close();
    }
} 




这篇关于如何避免通过winform将重复值输入表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:45
查看更多