如何在 C# 中编辑/更新 DataGridView 中的行



我正在研究像 WF 中的表单这样的购物车。我有一个DataGridViewADD_ButtonSubmit_Button.用户将从库存中选择项目,然后单击ADD_Button该项目将进入DataGridView完成后用户将单击Submit_Button然后详细信息将进入数据库。

问题:这是在将产品/行添加到DatagridView中后,当我添加相同的产品 again.it 进入新行时,我希望Pro_ID列匹配的地方,该行使用新数量更新。我试图搜索网络,但我得到了所有的SQL查询。

private void btn_Add_Click(object sender, EventArgs e)
{
i = dgv_Purchase.Rows.Count;
try
{
dgv_Purchase.Rows.Add();
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Pro_ID"].Value = txt_ProID.Text;
.......
.......
dgv_Purchase.Rows[i - 1].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
catch (Exception ){}
}

这是提交按钮代码

private void btnInsert_Click(Object sender, EventArgs e( { string cs = ConfigurationManager.ConnectionStrings["PRMSConnectionString"]。ToString((; SqlConnection con = new SqlConnection(cs(; SqlTransaction objTransaction;

for (int i = 0; i < dgv_Purchase.Rows.Count - 1; i++)
{
//SomeCode part of code
SqlCommand objCmd2;
string cmd2 = "INSERT INTO PurchaseMaster " +
" (Pro_ID , category_ID, Purchase_Qty) " +
"VALUES (@Pro_ID, @category_ID, @Purchase_Qty)";
objCmd2 = new SqlCommand(cmd2, con, objTransaction);
objCmd2.Parameters.AddWithValue("@Pro_ID_ID", dgv_Purchase.Rows[i].Cells["Pro_ID"].Value.ToString());
objCmd2.Parameters.AddWithValue("@Category_ID", dgv_Purchase.Rows[i].Cells["Category_ID"].Value.ToString());

objCmd2.Parameters.AddWithValue("@Purchase_Qty", Convert.ToInt32(dgv_Purchase.Rows[i].Cells["Purchase_Qty"].Value.ToString()));
objCmd2.Parameters.AddWithValue("@Date_Today", Convert.ToDateTime(dgv_Purchase.Rows[i].Cells["Purchase_Date"].Value.ToString()));
...........................
Rest of the Code
...........................
try
{
objCmd2.ExecuteNonQuery();
objTransaction.Commit();
}
catch (Exception) {}
} 
}

试试这个:

private void AddInfo()
{
// flag so we know if there was one dupe
bool updated = false;
// go through every row
foreach (DataGridViewRow row in dgv_Purchase.Rows)
{
// check if there already is a row with the same id
if (row.Cells["Pro_ID"].ToString() == txt_ProID.Text)
{
// update your row
row.Cells["Purchase_Qty"] = txt_Qty.Text;
updated = true;
break; // no need to go any further
}
}
// if not found, so it's a new one
if (!updated)
{
int index = dgv_Purchase.Rows.Add();
dgv_Purchase.Rows[index].Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}

我用DGVrow而不是DataRow编辑它

foreach (DataGridViewRow dr in dataGridView1.Rows)
{
if (dr.Cells["Pro_ID"].Value.ToString() == txt_ProID.Text)
{                      
dr.Cells["Purchase_Qty"].Value = txt_Qty.Text;
}
}

最新更新