【问题标题】:Looping through each row in a datagridview循环遍历datagridview中的每一行
【发布时间】:2013-11-02 00:10:39
【问题描述】:

如何遍历我读入的DataGridView 的每一行?在我的代码中,由于相同的 productID,行不会绑定到下一行,因此 DataGridView 不会移动到新行。它保持在同一行并覆盖价格(对于某些产品,我有两个价格)。如何遍历每一行以显示相同的 productID 但价格不同?

EX : 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

【问题讨论】:

  • 最好展示一张你想要的图片,或者你可以让帖子更清楚你真正想要的东西。我在您的帖子中理解的是,在您的 DataGridView 中,您想获取相同产品 ID 的总数量,但您想将两个或多个价格显示为一个?

标签: c# loops datagridview


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我使用下面的解决方案将所有数据网格值导出到文本文件,而不是使用列名,您可以使用列索引。

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

    【讨论】:

      【解决方案3】:

      对我来说最好的方法是:

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

      【讨论】:

      • 发帖抱歉,是关于自动增量列datagridview的其他主题
      猜你喜欢
      • 1970-01-01
      • 2014-06-29
      • 2015-04-14
      • 2012-11-08
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      相关资源
      最近更新 更多