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

VB.NET插入DataGridView内容到SQL Server表提示@Articulo参数未提供

错误原因
  • 最核心的诱因是遍历DataGridView时包含了控件默认生成的空白新增行,该行单元格值为Nothing。将Nothing赋值给SqlParameter的Value属性时,ADO.NET会判定该参数未被提供,而非传入空值,因此触发参数缺失异常。
  • 部分有效行的对应单元格值为DBNull或空引用时,未做兼容处理也会触发相同报错。
  • 小概率为DataGridView列索引映射错误,指定单元格无有效值。
解决方法

修改逻辑排除空白行,同时增加空值兼容处理即可,修正后的代码如下:

Private Sub btnGetTotal_Click(sender As Object, e As EventArgs) Handles btnGetTotal.Click
    ' Using块会自动释放连接、命令对象资源,无需手动关闭
    Using connection As New SqlConnection("你的数据库连接字符串")
        Using command As New SqlCommand("INSERT INTO Ordenes_Full (Articulo, Cantidad, Precio) VALUES (@Articulo, @Cantidad, @Precio)", connection)
            ' 请根据表字段实际长度调整参数长度,避免执行计划缓存异常
            command.Parameters.Add("@Articulo", SqlDbType.VarChar, 200)
            command.Parameters.Add("@Cantidad", SqlDbType.VarChar, 50)
            command.Parameters.Add("@Precio", SqlDbType.VarChar, 50)

            connection.Open()

            ' 遍历范围减1,跳过末尾的空白新增行
            For i As Integer = 0 To DataGridView1.Rows.Count - 2
                ' 空值兼容:值为空时显式传入数据库空值
                command.Parameters("@Articulo").Value = If(DataGridView1.Rows(i).Cells(0).Value IsNot Nothing, DataGridView1.Rows(i).Cells(0).Value, DBNull.Value)
                command.Parameters("@Cantidad").Value = If(DataGridView1.Rows(i).Cells(1).Value IsNot Nothing, DataGridView1.Rows(i).Cells(1).Value, DBNull.Value)
                command.Parameters("@Precio").Value = If(DataGridView1.Rows(i).Cells(2).Value IsNot Nothing, DataGridView1.Rows(i).Cells(2).Value, DBNull.Value)
                command.ExecuteNonQuery()
            Next
        End Using
    End Using
End Sub

额外注意事项

  • 如果你已经手动将DataGridView的AllowUserToAddRows属性设置为False,遍历范围不需要减1,保持原有的DataGridView1.Rows.Count - 1即可。
  • 建议用参数名访问参数,不要用索引,避免后续调整参数顺序时出现赋值错误。
  • 若Precio、Cantidad字段为数值类型,建议将参数类型调整为对应SqlDbType.Decimal/SqlDbType.Int,避免隐式类型转换报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 06:24:00