简体   繁体   English

只有第一行datagridview更新C#

[英]Only first row of datagridview updating c#

Below is my code for updating records in my Inventory table (ItemID is set as Primary Key). 以下是我的代码,用于更新“库存”表中的记录(ItemID设置为主键)。 The code works properly, however, it only updates the first row in the datagridview. 该代码正常工作,但是,它仅更新datagridview中的第一行。

Now, when I'm trying to update the other records (besides 1st row), I get this error message: "Column 'ItemID' is constrained to be unique. Value '2' is already present." 现在,当我尝试更新其他记录(第一行以外)时,收到以下错误消息:“列'ItemID'被限制为唯一。值'2'已经存在。” But when I update the first row, which is '1', it updates successfully, even though value '1' already exists. 但是,当我更新第一行“ 1”时,即使值“ 1”已经存在,它也会成功更新。

cb = new SqlCommandBuilder(da);

ds.Tables["Inventory"].Rows[0]["ItemID"] = txtID.Text;
ds.Tables["Inventory"].Rows[0]["ItemCode"] = txtCode.Text;
ds.Tables["Inventory"].Rows[0]["Description"] = txtDesc.Text;

da.Update(ds, "Inventory");
ds.Tables["Inventory"].AcceptChanges();
MessageBox.Show("Record updated successfully.");

I think I lack something in my code, any help would be appreciated. 我认为我的代码中缺少某些内容,我们将不胜感激。 Thanks. 谢谢。

Rather than setting the ItemID of the first row from your DS to the text value shouldn't you be finding the row in the DS that matches the ID entered. 不应在DS中找到与输入ID匹配的行,而不是将DS中第一行的ItemID设置为文本值。 My guess is when you update any other row aside from the first your DS ends up with the same ID twice. 我的猜测是,当您更新除第一行以外的任何其他行时,DS都会以相同的ID结束两次。

Before your update: 更新之前:

Row    ItemId
-----  ------
0      1
1      2
2      3

After your update for itemid 3: 更新itemid 3后:

Row    ItemId
-----  ------
0      3 <-- row 0 now contains id 3 which is a duplicate of row 2
1      2
2      3

I think the row update code would look something like this: 我认为行更新代码将如下所示:

cb = new SqlCommandBuilder(da);

var itemId = int.Parse(txtID.Text);
var row = ds.Tables["Inventory"].Rows.Find(itemId);
row["ItemCode"] = txtId.Text;
row["Description"] = txtId.Text;

da.Update(ds, "Inventory");
ds.Tables["Inventory"].AcceptChanges();
MessageBox.Show("Record updated successfully.");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM