InvalidCastException异常原因排查:在线商城项目运行报错
问题定位与修复方案
触发InvalidCastException的直接原因
你代码里的这一行是异常根源:
cartprice = Price * numQuantity.Text
numQuantity.Text是字符串类型,VB执行乘法时会隐式尝试将字符串转换为数值,如果输入内容不是有效整数(比如空值、字母、符号),就会抛出InvalidCastException。- 另外这里的
Price是大写,虽然VB不区分大小写,但建议统一为你定义的小写变量名price。
其他潜在问题及修复
- CheckedListBox选中项判断错误
clbParts.SelectedItem = 0逻辑错误,SelectedItem返回的是选中对象实例,不是索引值,应改用SelectedIndex:
If clbParts.SelectedIndex = 0 Then product = "Power Supply" price = 1 End If
- 数量验证逻辑位置错误
你现在是先计算价格再判断数量是否为0,应把验证移到最前面,避免无效计算:
If numQuantity.Text = "0" OrElse Not Integer.TryParse(numQuantity.Text, Nothing) Then MessageBox.Show("Please enter a valid positive number for quantity", "Cart Error") Exit Sub End If
- 总价计算逻辑错误
btnTotal_Click里的total += quantity + price是数量加单价,正确逻辑应为数量乘以单价:
total += quantity * price
- 拼写错误
rdo1tb分支里的Hard Drice需改为Hard Drive。
修复后的核心代码示例
修复后的btnAdd_Click方法
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click Dim prditem As ListViewItem Dim price, cartprice, quantity As Integer Dim product As String = String.Empty ' 先验证输入有效性 If Not Integer.TryParse(numQuantity.Text, quantity) OrElse quantity <= 0 Then MessageBox.Show("Please enter a valid positive number for quantity", "Cart Error") Exit Sub End If ' 处理CheckedListBox选中项 If clbParts.SelectedIndex = 0 Then product = "Power Supply" price = 1 ElseIf clbParts.SelectedIndex = 1 Then product = "CPU" price = 2 End If ' 处理单选按钮 If rdo512gb.Checked Then product = "Hard Drive (512GB)" price = 11 ElseIf rdo1tb.Checked Then product = "Hard Drive (1TB)" price = 12 End If ' 确保选中了商品 If String.IsNullOrEmpty(product) Then MessageBox.Show("Please select a product first", "Cart Error") Exit Sub End If ' 计算总价 cartprice = price * quantity ' 添加到购物车列表 prditem = lvCart.Items.Add(product) With prditem .SubItems.Add(quantity.ToString()) .SubItems.Add(cartprice.ToString()) End With MessageBox.Show("Item/s is/are added to your cart", "Cart") numQuantity.Text = "0" End Sub
修复后的btnTotal_Click方法
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click Dim total As Integer = 0 For i As Integer = 0 To lvCart.Items.Count - 1 Dim quantity = CInt(lvCart.Items(i).SubItems(1).Text) Dim price = CInt(lvCart.Items(i).SubItems(2).Text) total += quantity * price ' 修复为乘法逻辑 Next txtTotal.Text = total.ToString("N2") End Sub
内容的提问来源于stack exchange,提问作者Leonard Sinining
相关产品推荐
相关产品推荐

