在datagridview中循环遍历每一行

31
我该如何循环遍历读取的DataGridView中的每一行? 在我的代码中,由于相同的productID,行不会绑定到下一行,因此DataGridView不会移动到新行。它停留在同一行并覆盖价格(对于某些产品,我有两个价格)。我该如何循环遍历每一行,显示相同的productID但具有不同的价格?
例如:1个汉堡有2个价格--$1和$2。遍历数据后,结果应该有2行相同的产品但价格不同。我该怎么做?以下是我的代码:
productID = odr["product_id"].ToString();
quantity = Double.Parse(odr["quantity"].ToString());

//processing data...
key = productID.ToString();

if (key != key_tmp)
{
    //update index...
    i++;

    //updating variable(s)...
    key_tmp = key;
}

if (datagridviews.Rows[i].Cells["qty"].Value != null) //already has value...
{
    currJlh = Double.Parse(ddatagridviews.Rows[i].Cells["qty"].Value.ToString());
}
else //not yet has value...
{
    currQty = 0;
}
currQty += qty;

//show data...
datagridviews.Rows[i].Cells["price"].Value = cv.toAccountingCurrency_en(Double.Parse(odr["item_price"].ToString()));
MessageBoxes.Show(i.ToString());
MessageBoxes.Show(datagridviews.Rows[i].Cells["price"].Value.ToString()); // in here there is two price that looped but won't showed in datagridviews

1
最好展示您想要的图片,或者在帖子中更清晰地表达您真正想要的内容。据我理解,您在帖子中想要在 DataGridView 中获取相同产品 ID 的总数量,但是您想将两个或更多价格显示为一个? - Edper
3个回答

85
你可以使用 Rows 属性遍历 DataGridView,例如:
foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

3
我使用以下解决方案将所有数据网格值导出到文本文件,而不是使用列名,您可以使用列索引代替。
foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
    File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}

0

对我而言最好的方法是:

  private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        int X = 1;
        foreach(DataGridViewRow row in grid_receptie.Rows)
        {
            row.Cells["NR_CRT"].Value = X;
            X++;
        }
    }

1
抱歉打错了标题,应该是关于在DataGridView中自动递增列的问题。 - explorercris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接