2017-07-18 103 views
0

嗨,大家好,這裏是我的問題。我有2個datagridview。如果項目已經存在,則將值添加到datagridview中

我想要做的是,每當我點擊「這datagridview1行(產品)添加到datagridview2」,並從datagridview1該產品已經在datagridview2,它只會增加一個文本框(量)的值的數量細胞在datagridview2中具有與正在插入的ID相同的ID。

它可以檢測到您插入到datagridview2的產品是否已經存在,但是我不能讓它將該文本框的值添加到datagridview中的現有單元格。 這是我的代碼(這是錯誤的,不工作)和datagridviews的圖片。

private bool alreadyincart() 
    { 
     foreach (DataGridViewRow row in dgvOrdercart.Rows) 
     { 
      int productcartID = Convert.ToInt32(dgvOrderproductlist.CurrentRow.Cells[0].Value.ToString()); 
      if (Convert.ToInt32(row.Cells[0].Value) == productcartID) 
      { 
       MessageBox.Show("Item already exist, Adding the quantity instead."); 
       int textboxquantity = Convert.ToInt32(bakss.Text); 
       int dgvquantity = Convert.ToInt32(row.Cells[3].Value); 
       int dgvnewquantity; 
       dgvnewquantity = dgvquantity + textboxquantity; 
       dgvOrdercart.Rows[productcartID].Cells[3].Value = dgvnewquantity; 
       return false; 

      } 
     } 
     return true; 
    } 

    private void btnAdd_Click(object sender, EventArgs e) 
    { 
     if (!validate()) 
     { 
      return; 
     } 
     else if (!alreadyincart()) 
     { 
      return; 
     } 
     else 
     { 
      addData(dgvOrderproductlist.CurrentRow.Cells[0].Value.ToString(), 
       dgvOrderproductlist.CurrentRow.Cells[1].Value.ToString(), 
       dgvOrderproductlist.CurrentRow.Cells[2].Value.ToString(), 
       bakss.Text, lblPrice.Text, totalprayss.Text, cboOrderSupplier.SelectedItem.ToString());   
     } 
    } 

enter image description here

+0

你的邏輯是一種倒退,使其難以跟隨你的代碼。 '當購物車中出現**時,alreadyincart()'返回false,當找不到時爲true。這與它應該是相反的。 – AgapwIesu

+0

是的,我注意到很抱歉的混亂! – FutureDev

回答

1

試圖改變

dgvOrdercart.Rows[productcartID].Cells[3].Value = dgvnewquantity; 

row.Cells[3].Value = dgvnewquantity; 
+1

這就是答案。由於購物車100103的第0行中的產品ID,您的代碼嘗試訪問第100103行,而不是第0行。沒有第100103行。 – AgapwIesu

+0

非常感謝您! – FutureDev

+0

確保你接受他的答案。 – AgapwIesu

相關問題