[英]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.