简体   繁体   中英

DataGridView Cell Editing and Updating DB (C#)

I have a function to edit a cell in my dgv. And that is the problem. I can only edit one cell.

Here is my code so far:

        private void datagridview1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
        Connection();
        sqlconnection.Open();

        this.datagridview1.Rows[e.RowIndex].Selected = true;
        this.rowIndex1 = e.RowIndex;
        this.datagridview1.CurrentCell = this.datagridview1.Rows[e.RowIndex].Cells[1]; //1 = only quantity can be edited, 0 = only item can be edited

        sqlcmd = new SqlCommand("UPDATE inventory_table SET item = @item, quantity = @quantity WHERE id= " + this.datagridview1.Rows[this.rowIndex1].Cells["id"].Value, sqlconnection);
        sqlcmd.Parameters.AddWithValue("@item", this.datagridview1.Rows[this.rowIndex1].Cells["item1"].Value);
        sqlcmd.Parameters.AddWithValue("@quantity", this.datagridview1.Rows[this.rowIndex1].Cells["quantity1"].Value);
        sqlcmd.ExecuteNonQuery();

        sqlconnection.Close();
        }

What am I missing? And what could I do so that I can edit multiple dgv cells and have them get updated in the DB?

I believe that the problem is due to using the wrong event. You appear to want to execute an update when the user finishes editing a row.

But your code lives in an event that fires after any cell finishes editing. I can't say for certain what event you want. That is dependent on your specifications.

But I'll bet that the RowValidated event will meet your needs. If not, check out the RowStateChanged event. (And try the sample code for that event. It should help you to get a feel for when the event fires.)

you can't update or delete multiple rows in gridview using gridview editing or deleting method, i believe there are no default events in gridview to update or delete multiple records.

but you can achieve this by using another procedure:

1>you can take a button in gridview footer or outside the grid view,after putting all updated value to the grid cell write code on footer_button click to update all records in the gridview. 2>you can use jQuery/ajax control on grid to update grid record on textbox_leave event.

Some samples you can look for the solution

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