![](/img/trans.png)
[英]How to add a new row to the datagridview and edit it in C# winform?
[英]How to Edit/Update a row in DataGridView in C#
我正在處理像 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(object sender, EventArgs e) { string cs = ConfigurationManager.ConnectionStrings["PRMSConnectionString"].ToString(); SqlConnection con = new SqlConnection(cs); SqlTransaction 對象事務;
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) {}
}
}
我用 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;
}
}
嘗試這個:
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.