exception occur i my code is:
Violation of PRIMARY KEY constraint 'PK__lib_book__1ADC427003317E3D'. Cannot insert duplicate key in object 'dbo.lib_book_details'.
The statement has been terminated.

SqlConnection cs = new SqlConnection("Data Source=IRIS-CSG-174;Initial Catalog=library_system;Integrated Security=True");
            SqlDataAdapter da = new SqlDataAdapter();
            da.UpdateCommand = new SqlCommand("Update Lib_book_details set book_tag_id=@book_tag_id,book_name=@book_name,book_author_name=@book_author_name where book_category_id=@book_category_id", cs);
            da.UpdateCommand.Parameters.Add("@book_tag_id", SqlDbType.Int).Value = textBox1.Text;
            da.UpdateCommand.Parameters.Add("@book_name", SqlDbType.VarChar).Value = textBox2.Text;
            da.UpdateCommand.Parameters.Add("@book_category_id", SqlDbType.Int).Value = Convert.ToInt32(comboBox1.SelectedValue);
            da.UpdateCommand.Parameters.Add("@book_author_name", SqlDbType.VarChar).Value = textBox3.Text;
            cs.Open();
            MessageBox.Show("new book updated!");
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();

Recommended Answers

All 2 Replies

You are trying to insert a record that has the same primary key as another record. How is your table defined?

If you are updating an existing row in the dataTable, you MUST put a comparison, this is a WHERE clause in the sql query.
And you cannot update ID, which is a uniqe key. The Id you have to use to compare which row you have to update.
How you will get this Id its up to you, but you should have got it, before when you did a select query (and remember it some how).
The query should look like this:

da.UpdateCommand = new SqlCommand("Update Lib_book_details set book_name=@book_name,book_author_name=@book_author_name where book_category_id=@book_category_id [B]WHERE book_tag_id=@book_tag_id[/B]", cs);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.