Reputation: 36
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?
Upvotes: 0
Views: 7704
Reputation: 35380
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.
Upvotes: 0
Reputation: 340
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
Upvotes: 0
Reputation: 10429
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
Upvotes: 1