简体   繁体   中英

Only first row of datagridview updating c#

Below is my code for updating records in my Inventory table (ItemID is set as Primary Key). The code works properly, however, it only updates the first row in the 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." But when I update the first row, which is '1', it updates successfully, even though value '1' already exists.

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. My guess is when you update any other row aside from the first your DS ends up with the same ID twice.

Before your update:

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

After your update for 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.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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