简体   繁体   中英

C# DataGridView how to get all row values via loop?

I need to get all the values of two columns in a row and multiply it and add the the product of the two column for each row

 foreach (DataGridViewRow row in dataGridView2.Rows)
        {
            int currPrice = Convert.ToInt32(row.Cells[1].Value.ToString());
            int currQuan = Convert.ToInt32(row.Cells[2].Value.ToString());
            int newPrice = currPrice++;
            int newQuan = currQuan++;
            int newTotal = newPrice * newQuan;
            textBox4.Text = newTotal.ToString();
        }

it works but only in the selected row.

For example in the datagrid I have 2 rows

the first rows price is 10 and the quantity is 20 so I need to get its product and do the same thing for the other row and once it is all finished for all the rows, It should add it all/get the sum

my number of rows is not predetermined so it should be dynamic, How am I suppose to do this?

Your total variable should be out of the loop something like

int total=0;
foreach (DataGridViewRow row in dataGridView2.Rows)
        {
            int currPrice = Convert.ToInt32(row.Cells[1].Value.ToString());
            int currQuan = Convert.ToInt32(row.Cells[2].Value.ToString());
            total += currPrice * currQuan ;
        }

textBox4.Text = newTotal.ToString();

Also i didn't get the reason why you are using post increment oprator here

You are re-creating the variables on each iteration (other than newTotal , no big deal but it makes you code slower). Try defining the variables outside the loop.

int currPrice, currQuan, newPrice, newQuan;
int newTotal = 0; //this needs to be initialized in case grid is empty.

foreach (DataGridViewRow row in dataGridView2.Rows)
{
    currPrice = Convert.ToInt32(row.Cells[1].Value.ToString());
    currQuan = Convert.ToInt32(row.Cells[2].Value.ToString());

    // not sure why these are incremented prior to calculating the total
    // maybe the total shoud use currPrice and currQuan, as suggested by jitender.
    newPrice = ++currPrice;
    newQuan = ++currQuan;

    newTotal += newPrice * newQuan;
}

textBox4.Text = newTotal.ToString(); // Update the display after we do all the math

As mentioned in comments, I changed from post-increment to pre-increment , and made the newTotal a real sum

If you like LINQ, this can also be done in a single line without using an explicit loop.

textBox4.Text = dataGridView2.Rows.Cast<DataGridRow>().Sum(r => 
                            Convert.ToInt32(r.Cells[1].Value.ToString()) *
                            Convert.ToInt32(r.Cells[2].Value.ToString())).ToString();

You must import System.Linq at the top of this file for the above code to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM