【问题标题】:Add value instead to datagridview if item already exist如果项目已经存在,则将值添加到 datagridview
【发布时间】:2017-12-23 18:35:54
【问题描述】:

大家好,这是我的问题。我有 2 个数据网格视图。

我想要做的是每当我点击“将此datagridview1行(产品)添加到datagridview2”并且来自datagridview1的产品已经在datagridview2中时,它只会将文本框(数量)的值添加到数量单元格中datagridview2 与被插入的 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());           
        }
    }

【问题讨论】:

  • 你的逻辑有点倒退,让你的代码更难遵循。 alreadyincart() 在购物车中找到 时返回 false,在未找到时返回 true。这与应有的相反。
  • 是的,我注意到很抱歉造成混乱!

标签: c# datagridview


【解决方案1】:

尝试改变

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

row.Cells[3].Value = dgvnewquantity;

【讨论】:

  • 这就是答案。由于购物车 100103 的第 0 行中的产品 ID,因此您的代码尝试访问第 100103 行,而不是第 0 行。没有第 100103 行。
猜你喜欢
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
相关资源
最近更新 更多