Reputation: 353
I m working on a shopping cart like Form in WF. I have a DataGridView
an ADD_Button
and Submit_Button
.The user will choose Items From inventory and Click ADD_Button
The item will go into DataGridView
After Finishing User will click Submit_Button
then detail will go into DB.
Question: is this After adding a product/row into DatagridView
When I add same product again.it goes into the new row I want that Where Pro_ID
Column Match, The row update with new qty. I tried to search the web but all I got SQL queries.
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 ){}
}
This is Submit Button Code
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) {}
}
}
Upvotes: 0
Views: 10668
Reputation: 1
I edit it with a DGVrow instead of 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;
}
}
Upvotes: 0
Reputation: 560
Try this:
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;
}
}
Upvotes: 1