DataGridView单元格编辑和更新DB(C#) [英] DataGridView Cell Editing and Updating DB (C#)
问题描述
这是我的代码到目前为止:
private void datagridview1_CellEndEdit对象发件人,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 =只可以编辑数量,0 =只能编辑项目
sqlcmd = new SqlCommand(UPDATE inventory_table SET item = @item,quantity = @quantity WHERE id =+ this。 datagridview1.Rows [this.rowIndex1] .Cells [id]。值,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单元格并让它们在DB中更新?
我相信问题是由于使用错误的事件。您似乎希望在用户完成编辑行时执行更新。
但您的代码存在于任何单元格完成编辑后触发的事件。我不能说你想要什么事情。这取决于你的规格。
但是我敢打赌 RowValidated 事件将满足您的需求。如果没有,请查看 RowStateChanged 事件。 (并尝试该事件的示例代码,它可以帮助您了解事件触发时的感觉。)
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.)
这篇关于DataGridView单元格编辑和更新DB(C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!