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

VB.NET中向DataGridView行插入数值遇阻,寻求解决方案

VB.NET DataGridView行插入数值问题修复

问题情况

我在VB.NET里给DataGridView的行插入数值时碰到了问题,现在的代码是这样的:

Dim subtotal As Integer = Val(adult.Text) * 500 + Val(child.Text) * 300

For Each row As DataGridViewRow In DataGridView2.Rows
    row.Cells.Insert(subtotal)
Next

想要实现的效果是把计算出的小计值插入到DataGridView的对应列(类似示例里的“Subtotal”列),让每一行都显示这个计算结果。

问题出在哪

原代码的错误很明显:

  • row.Cells.Insert()方法需要的是列索引和单元格对象,直接传数值subtotal完全不符合参数要求
  • 循环遍历所有行时,没排除DataGridView自带的空行模板,容易引发异常

修复代码

按照需求,正确的做法是找到目标列,给每一行的该列赋值,而非调用Insert方法。修复后的代码如下:

' 先计算小计值
Dim subtotal As Integer = Val(adult.Text) * 500 + Val(child.Text) * 300

' 遍历DataGridView的有效行,跳过最后一行的空模板
For Each row As DataGridViewRow In DataGridView2.Rows
    If Not row.IsNewRow Then
        ' 假设目标列的名称是"Subtotal",直接通过列名赋值
        row.Cells("Subtotal").Value = subtotal
        ' 如果知道列的索引,也可以用索引赋值,比如第4列就写row.Cells(3).Value = subtotal
    End If
Next

额外优化建议

  • 别用Val处理输入,推荐用Integer.TryParse,能防止输入非数字内容时出错:
    Dim adultCount, childCount As Integer
    Integer.TryParse(adult.Text, adultCount)
    Integer.TryParse(child.Text, childCount)
    Dim subtotal As Integer = adultCount * 500 + childCount * 300
    
  • 如果你的需求是新增一行然后插入数值,而非修改已有行,那就用Rows.Add方法:
    ' 示例:添加包含多列数据的行,最后一个是小计
    DataGridView2.Rows.Add("成人票", adultCount, 500, subtotal)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:01:01