30

How do I loop through each row of a DataGridView that I read in? In my code, the rows won't bind to the next row because of the same productID, so the DataGridView won't move to a new row. It stays on the same row and overwrites the price (for some products, I have two prices). How do I loop through each row to show the same productID but have a different price?

EX : 1 Hamburger has 2 prices -- $1 and $2. After looping through the data, the result should have 2 rows with the same product but different pricing. How do I do this? Below is my code:

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
Ke Vin
  • 3,478
  • 11
  • 60
  • 91
  • 1
    It is better to show a picture of what you want or you could make post clearer on what you really want. What I understood in your post is that in your DataGridView you want to get the Total Quantity of the same product ID but you want to show the two or more prices as one? – Edper Nov 02 '13 at 02:41

3 Answers3

85

You could loop through DataGridView using Rows property, like:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}
Edper
  • 9,144
  • 1
  • 27
  • 46
2

I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.

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);
}
41 72 6c
  • 1,600
  • 5
  • 19
  • 30
-1

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