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

如何在DataGridView中统计数字列数据并添加总计行

VB.NET中给DataGridView添加总计行的实现方案

你现在有这样的DataGridView数据:

S.NData1Data2
1-10
242
32-
49-

想要在现有数据下方添加总计行,统计Data1和Data2列的数字总和,最终得到这样的效果:

S.NData1Data2
1-10
242
32-
49-
total1512

你尝试了部分VB.NET代码但没完成,我来帮你补全并修正其中的问题,完整代码如下:

Dim data1 As Double = 0
Dim data2 As Double = 0

' 遍历所有有效数据行(排除默认的空白新行)
For i As Integer = 0 To DataGridView1.RowCount - 2
    ' 处理Data1列:仅当单元格值不为空且不是"-"时累加
    If DataGridView1.Rows(i).Cells(1).Value IsNot Nothing AndAlso 
       DataGridView1.Rows(i).Cells(1).Value.ToString() <> "-" Then
        data1 += CDbl(DataGridView1.Rows(i).Cells(1).Value)
    End If
    
    ' 处理Data2列:同样判断非空非"-"再累加
    If DataGridView1.Rows(i).Cells(2).Value IsNot Nothing AndAlso 
       DataGridView1.Rows(i).Cells(2).Value.ToString() <> "-" Then
        data2 += CDbl(DataGridView1.Rows(i).Cells(2).Value)
    End If
Next

' 创建并添加总计行
Dim newRow As DataGridViewRow = New DataGridViewRow()
newRow.CreateCells(DataGridView1)
newRow.Cells(0).Value = "total"
newRow.Cells(1).Value = data1
newRow.Cells(2).Value = data2
' 给总计行设置加粗样式,区分普通数据行
newRow.DefaultCellStyle.Font = New Font(DataGridView1.Font, FontStyle.Bold)
DataGridView1.Rows.Add(newRow)

关键说明:

  • 遍历范围调整:用RowCount - 2是因为DataGridView默认最后一行是空白的可编辑新行(AllowUserToAddRows默认开启),排除这一行能避免空值转换报错。
  • 空值与特殊值判断:增加了对单元格值是否为空、是否为"-"的判断,直接转换这类值会引发错误,先过滤再累加才准确。
  • 样式优化:给总计行设置加粗字体,让它在表格里更醒目,你可以根据需求修改样式(比如背景色、字体颜色等)。

内容的提问来源于stack exchange,提问作者Pradip Dhakal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:20:24