【问题标题】:C# DataGridView how to get all row values via loop?C# DataGridView 如何通过循环获取所有行值?
【发布时间】:2018-02-27 16:49:46
【问题描述】:

我需要获取一行中两列的所有值并将其相乘并为每一行添加两列的乘积

 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,所以我需要得到它的产品并对另一行做同样的事情,一旦所有行都完成了,它应该把它全部加起来/得到总和

我的行数不是预先确定的,所以它应该是动态的,我应该怎么做?

【问题讨论】:

    标签: c# loops for-loop datagridview foreach


    【解决方案1】:

    你的总变量应该像

    这样的循环
    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();
    

    我也没有明白你在这里使用后增量运算符的原因

    【讨论】:

    • 感谢它的工作!我认为后增量是总和的必要条件。尽管如此,还是非常感谢你。
    • 感谢它的工作!我认为后增量是总和的必要条件。尽管如此,还是非常感谢你。
    • 嘿再次感谢您的帮助我们刚刚通过了我们的防御
    【解决方案2】:

    您在每次迭代时重新创建变量(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
    

    如 cmets 中所述,我将 post-increment 更改为 pre-increment,并将 newTotal 设为真正的 sum

    【讨论】:

    • 这里的currPrice++和currQuan++有什么用?
    • 还有 newTotal = newPrice * newQuan;将乘以最后一行应该是 newTotal += newPrice * newQuan
    • 如果很可能是发布者方面的错误,则使用后增量。它将在递增之前返回值。
    【解决方案3】:

    如果您喜欢 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 才能使上述代码正常工作。

    【讨论】:

      猜你喜欢
      • 2021-05-28
      • 1970-01-01
      • 2019-10-05
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多