Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a sql table having fields ItemID(set as primary key), ItemCategoryID,newid(set as uniqueidentifier)

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        int ItemID = 1123342;
        int ItemCategoryID =1;
}


SqlCommand cmd = new SqlCommand("insert into Item(ItemID,ItemCode,ItemCategoryID,ItemDescription) values(@ItemID,@ItemCategoryID)", con);
cmd.Parameters.AddWithValue("@ItemCode", txtItemCode.Text);
cmd.Parameters.AddWithValue("@ItemDescription", txtItemDescription.Text);
cmd.Parameters.AddWithValue("@ItemID", ItemID);
cmd.Parameters.AddWithValue("@ItemCategoryID",ItemCategoryID);
cmd.ExecuteNonQuery();
}
Whenever I click submit button at first the value will be inserted to db. But in the second click it shows that :
SQL
Violation of PRIMARY KEY constraint 'PK_Item'. Cannot insert duplicate key in object 'dbo.aItem'. The duplicate key value is (1123342).
The statement has been terminated.
Posted

you cannot have same values in primary column it needs to have distinct values
 
Share this answer
 
since ItemID is primary key, it should be unique. When you click for the second time, the same value for ItemID gets passed and hence you are getting the message. Make sure you change the ItemID for each and every item.
 
Share this answer
 
Comments
My Doubt 26-Mar-14 7:11am    
Yes you are right. But I need to know how to increment the ItemID on every click. It is initially set as ItemID = 1123342.
Naz_Firdouse 26-Mar-14 7:30am    
Define ItemID as a global variable and increment its value on button click itself so that whenever you click , its value gets incremented and you can insert them in DB
Naz_Firdouse 26-Mar-14 7:31am    
if it sovles your issue, vote up and mark as answer
My Doubt 27-Mar-14 0:09am    
I think I need to create an sp to solve this problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900