C# 循环datagridview中的每一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19737436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:47:04  来源:igfitidea点击:

Looping each row in datagridview

c#loopsdatagridview

提问by Ke Vin

How to loop each row that readed? in my code, the row won't bind to next row because of the same productID, so the datagridview won't move to new row, it still in the same row and overwrite the price (for some product, i have two price). How to loop it to show the same productID but it have different price.

如何循环读取的每一行?在我的代码中,由于相同的 productID,该行不会绑定到下一行,因此 datagridview 不会移动到新行,它仍然在同一行并覆盖价格(对于某些产品,我有两个价格) . 如何循环它以显示相同的 productID 但它有不同的价格。

EX : 1 Hamburger have 2 price Hamburger : $1 and $2 when i get the data with looping it, the resould shoult be have 2 Row with same product but different price. How to do this? below is my code

例如: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

help me out :)

帮帮我 :)

采纳答案by Edper

You could loop through DataGridViewusing Rowsproperty, like:

您可以循环DataGridView使用Rows属性,例如:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

回答by explorercris

Best aproach for me was:

对我来说最好的方法是:

  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++;
        }
    }