DataGridView 单元格编辑和更新数据库 (C#)

DataGridView Cell Editing and Updating DB (C#)

我有一个功能可以编辑我的 dgv 中的单元格。这就是问题所在。我只能编辑一个单元格。

到目前为止,这是我的代码:

        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();
        }

我错过了什么?我该怎么做才能编辑多个 dgv 单元格并让它们在数据库中更新?

我认为问题是由于使用了错误的事件。您似乎想要在用户完成对行的编辑时执行更新。

但是您的代码存在于任何单元格完成编辑后触发的事件中。我不能确定你想要什么事件。这取决于您的规格。

但我敢打赌 RowValidated event will meet your needs. If not, check out the RowStateChanged 事件。 (并尝试该事件的示例代码。它应该可以帮助您了解事件何时触发。)

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.

您可以寻找解决方案的一些示例