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

InvalidCastException异常原因排查:在线商城项目运行报错

问题定位与修复方案

触发InvalidCastException的直接原因

你代码里的这一行是异常根源:

cartprice = Price * numQuantity.Text
  • numQuantity.Text是字符串类型,VB执行乘法时会隐式尝试将字符串转换为数值,如果输入内容不是有效整数(比如空值、字母、符号),就会抛出InvalidCastException。
  • 另外这里的Price是大写,虽然VB不区分大小写,但建议统一为你定义的小写变量名price。

其他潜在问题及修复

  1. CheckedListBox选中项判断错误
    clbParts.SelectedItem = 0 逻辑错误,SelectedItem返回的是选中对象实例,不是索引值,应改用SelectedIndex:
If clbParts.SelectedIndex = 0 Then
    product = "Power Supply"
    price = 1
End If
  1. 数量验证逻辑位置错误
    你现在是先计算价格再判断数量是否为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
  1. 总价计算逻辑错误
    btnTotal_Click里的total += quantity + price 是数量加单价,正确逻辑应为数量乘以单价:
total += quantity * price
  1. 拼写错误
    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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:25:15