[英]C# DataGridView how to get all row values via loop?
我需要获取一行中两列的所有值并将其相乘并为每一行添加两列的乘积
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();
}
它有效,但仅在所选行中有效。
例如在数据网格中,我有2行
第一行的价格是10,数量是20,所以我需要获取它的产品并为另一行做同样的事情,一旦所有行都完成了,它应该全部加/获得总和
我的行数不是预先确定的,因此应该是动态的,我应该怎么做?
您的总变量应该像这样循环
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();
我也没有得到你为什么在这里使用后增量运算符的原因
您将在每次迭代中重新创建变量(除了newTotal
,没什么大不了的,但是这会使您的代码编写速度变慢)。 尝试在循环外定义变量。
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
如评论中所述,我从后递增更改为前递增 ,并使newTotal
为实数
如果您喜欢LINQ,也可以在一行中完成,而无需使用显式循环。
textBox4.Text = dataGridView2.Rows.Cast<DataGridRow>().Sum(r =>
Convert.ToInt32(r.Cells[1].Value.ToString()) *
Convert.ToInt32(r.Cells[2].Value.ToString())).ToString();
您必须在此文件的顶部导入System.Linq
,以上代码才能起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.