You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对GridView中匹配选定行Le Nom值的Quantity列求和?

问题描述

我需要实现对GridView控件中,与选定行“Le Nom”列值相同的所有行的“Quantity”列数值求和。示例数据如下:

Le Nom   Quantity
HEA200   200
HEB300   150
IPE450   700
HEA200   300

例如选中第一行时,需将“HEA200”对应的200和300求和。当前我能实现所有值的求和,但无法达成目标,现有代码如下:

int sum = 0;
string NameProfil = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "Le Nom").ToString();
for (int i = 0; i < gridView2.RowCount; i++)
{
    sum += int.Parse(Convert.ToString(gridView2.GetRowCellValue(i, "Quantit茅")));
}
MessageBox.Show(sum.ToString() + " " + NameProfil);
解决方法

我看了下你的代码,问题很明显:你现在是把所有行的Quantity都累加了,没有判断当前行的“Le Nom”值是否和选中行的一致。只要在循环里加个判断条件就能解决问题,具体修改如下:

  1. 保留你已经正确获取选中行“Le Nom”值的代码;
  2. 遍历每一行时,先获取当前行的“Le Nom”值;
  3. 对比当前行的“Le Nom”和选中行的NameProfil,只有相等时才累加该行的Quantity。

修改后的完整代码:

int sum = 0;
// 获取选中行的Le Nom值
string selectedNom = gridView2.GetRowCellValue(gridView2.FocusedRowHandle, "Le Nom").ToString();

for (int i = 0; i < gridView2.RowCount; i++)
{
    // 获取当前行的Le Nom值
    string currentNom = gridView2.GetRowCellValue(i, "Le Nom").ToString();
    // 判断是否和选中行的Nom一致
    if (currentNom.Equals(selectedNom))
    {
        // 累加对应的Quantity
        sum += int.Parse(Convert.ToString(gridView2.GetRowCellValue(i, "Quantit茅")));
    }
}
MessageBox.Show(sum.ToString() + " " + selectedNom);

额外提示

  • 注意列名的拼写:你的代码里用了Quantit茅,要确保和GridView里实际的列名完全一致(包括重音符号);
  • 如果数据里可能存在空值或者非数字的Quantity,建议加个异常判断,比如用int.TryParse来避免程序崩溃:
    if (currentNom.Equals(selectedNom))
    {
        string quantityStr = Convert.ToString(gridView2.GetRowCellValue(i, "Quantit茅"));
        if (int.TryParse(quantityStr, out int quantity))
        {
            sum += quantity;
        }
    }
    

内容的提问来源于stack exchange,提问作者M.Bouabdallah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:35:12