我正在使用WF中的Form这样的购物车。我有一个DataGridView
和一个ADD_Button
和Submit_Button
。用户将选择清单中的项目,然后单击ADD_Button
,该项目将在完成后进入DataGridView
用户将单击Submit_Button
,然后详细信息将进入数据库。
问题:是这样吗?在向DatagridView
添加产品/行之后,当我再次添加相同的产品时,它进入新行,我希望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(对象发送者,EventArgs e) { 字符串cs = ConfigurationManager.ConnectionStrings [“ PRMSConnectionString”]。ToString(); SqlConnection con =新的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) {}
}
}
答案 0 :(得分:0)
我用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;
}
}
答案 1 :(得分:0)
尝试一下:
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;
}
}