DataGridView重复搜索后总价计算错误的原因及修复方案
问题分析与修改方案
核心错误点
总价计算列索引错误
首次添加行时,数据库字段totalprice(列索引7)可能未正确赋值(或数据库中值为0),你错误地用该列值乘以数量,导致总价显示0。实际应使用不含税单价(列5)+ 税额的逻辑重新计算总价。数量更新写法冗余
CInt("1") + numtext属于不必要的字符串转整数操作,直接用numtext + 1更简洁可靠。单元格值未做类型转换
直接读取Cells.Value进行计算时,未处理类型转换,可能因类型不匹配导致计算异常。SQL注入风险
使用字符串拼接SQL语句存在注入漏洞,需改用参数化查询。
修改后的完整代码
Dim exist As Boolean = False, numrow As Integer = 0, numtext As Integer ' 遍历行时跳过新行(避免空值判断) For Each itm As DataGridViewRow In DataGridView1.Rows If Not itm.IsNewRow Then If itm.Cells(1).Value.ToString = txt_searchProduct_barcode.Text Then exist = True numrow = itm.Index numtext = CInt(itm.Cells(8).Value) Exit For End If End If Next If exist = False Then Try conn.Open() ' 使用参数化查询避免SQL注入 cmd = New MySqlCommand("SELECT * FROM `tblproduct` WHERE `procode`=@procode", conn) cmd.Parameters.AddWithValue("@procode", txt_searchProduct_barcode.Text) dr = cmd.ExecuteReader While dr.Read() If String.IsNullOrEmpty(txt_searchProduct_barcode.Text) Then Return End If Dim procode As String = dr("procode").ToString() Dim Proname As String = dr("proname").ToString() Dim Progroup As String = dr("progroup").ToString() Dim uom As String = dr("uom").ToString() Dim Price As Decimal = Convert.ToDecimal(dr("price")) Dim tax As Decimal = Convert.ToDecimal(dr("tax")) ' 计算含税单价和总价(数量1时) Dim taxAmount As Decimal = Price * tax / 100 Dim totalqtyprice As Decimal = (Price + taxAmount) * 1 DataGridView1.Rows.Add( DataGridView1.Rows.Count + 1, procode, Proname, Progroup, uom, Price, tax, dr("totalprice"), ' 保留原数据库字段,若不需要可移除 1, totalqtyprice ) End While Catch ex As Exception MsgBox(ex.Message) Finally conn.Close() End Try Else ' 更新数量:原数量+1 Dim newQty As Integer = numtext + 1 DataGridView1.Rows(numrow).Cells(8).Value = newQty ' 从单元格读取单价和税率,重新计算含税总价 Dim price As Decimal = Convert.ToDecimal(DataGridView1.Rows(numrow).Cells(5).Value) Dim taxRate As Decimal = Convert.ToDecimal(DataGridView1.Rows(numrow).Cells(6).Value) Dim taxAmount As Decimal = price * taxRate / 100 Dim totalPrice As Decimal = (price + taxAmount) * newQty DataGridView1.Rows(numrow).Cells(9).Value = totalPrice End If End Sub
额外优化说明
- 遍历行时用
Not itm.IsNewRow替代空值判断,更符合DataGridView的行特性。 - 对数据库读取的字段添加
ToString()和类型转换,避免空值或类型不匹配问题。 - 参数化查询彻底解决SQL注入风险,同时提升代码可读性。
内容的提问来源于stack exchange,提问作者misteriomarcos
相关产品推荐
相关产品推荐

