如何在按钮点击时设置自动增量主键? [英] How to set auto increment primary key on button click?

查看:70
本文介绍了如何在按钮点击时设置自动增量主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个包含字段ItemID(设置为主键),ItemCategoryID,newid(设置为uniqueidentifier)的sql表



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(插入Item(ItemID,ItemCode,ItemCategoryID,ItemDescription)值(@ 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();

}

每当我点击提交按钮时,该值将被插入数据库。但在第二次单击时,它显示:



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 :

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.

推荐答案

您不能在主列中拥有相同的值,它需要具有不同的值
you cannot have same values in primary column it needs to have distinct values


因为ItemID是主键,所以它应该是唯一的。当您第二次单击时,ItemID的相同值将被传递,因此您将收到消息。确保更改每个项目的ItemID。
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.


这篇关于如何在按钮点击时设置自动增量主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆