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

VB.NET中ListBox.Add拼接字符串与数值引发类型转换异常问题

VB.NET字符串与数值拼接触发类型转换异常问题解析

问题描述

编写btnprocess_Click事件代码时,尝试在ListBox.Items.Add语句中同时拼接字符串与Decimal类型数值,触发异常:"Conversion from string "Number of Chairs:" to type 'Double' is not valid."

问题代码

Private Sub btnprocess_Click(sender As Object, e As EventArgs) Handles btnprocess.Click
    Dim FullName As String = txtfullname.Text
    Dim comma As Integer = FullName.IndexOf(",")
    Dim Lname As String = FullName.Substring(0, comma)
    Dim Fname As String = FullName.Substring(comma + 2)
    Dim Lfirst As String = Lname.Substring(0, 1)
    Dim Ffirst As String = Fname.Substring(0, 1)
    Dim CSZ As String = txtlocation.Text
    Dim FourthC As String = CSZ.Length() - 4
    Dim zipfour As String = CSZ.Substring(FourthC)
    Dim strAdress As String
    Dim decchairs As Decimal
    Dim decsofas As Decimal
    decchairs = CDec(txtchairs.Text)
    decsofas = CDec(txtsofas.Text)
    Dim decPrice As Decimal = (decsofas * 925) + (decchairs * 350)


    strAdress = CStr(txtadress.Text)
    strAdress = CStr(txtadress.Text)
    ListBox1.Items.Add("Invoice Number:" + Ffirst + Lfirst + FourthC)
    ListBox1.Items.Add("Name:" + Fname + Lname)
    ListBox1.Items.Add("Adress:" + strAdress)
    ListBox1.Items.Add("City:" + CSZ)
    ListBox1.Items.Add("Number of Chairs:" + decchairs)
    ListBox1.Items.Add("Number of Sofas:" + decsofas)
    ListBox1.Items.Add("Number of Chairs:" + decchairs)
    ListBox1.Items.Add("Price:" + decPrice)
    ListBox1.Items.Add("Sales Tax:" + (decPrice * 0.05))
    ListBox1.Items.Add("Total Price:" + decPrice + (decPrice * 0.05))
End Sub

问题原因与解决方案

核心问题:+运算符的歧义

VB.NET中+运算符存在双重作用:

  • 当两边均为字符串时,执行字符串拼接
  • 当一边是字符串、一边是数值类型时,VB会尝试将字符串转换为数值,执行算术加法

你遇到的异常就是因为代码中用+拼接字符串和Decimal(如"Number of Chairs:" + decchairs),VB尝试把字符串"Number of Chairs:"转成Double做加法,自然失败。

解决方法

有两种可靠的方式实现字符串与数值的拼接:

  1. 使用&运算符:这是VB.NET专门用于字符串拼接的运算符,无论两边是什么类型,都会先转成字符串再拼接
    示例:
    ListBox1.Items.Add("Number of Chairs:" & decchairs)
    ListBox1.Items.Add("Price:" & decPrice)
    ListBox1.Items.Add("Total Price:" & (decPrice + decPrice * 0.05))
    
  2. 显式将数值转成字符串:调用数值类型的ToString()方法,再用+拼接
    示例:
    ListBox1.Items.Add("Number of Chairs:" + decchairs.ToString())
    ListBox1.Items.Add("Sales Tax:" + (decPrice * 0.05).ToString())
    

额外的代码问题修正

除了拼接问题,代码里还有两个小问题需要注意:

  • FourthC被声明为String类型,但它是CSZ.Length() - 4的计算结果(整数),应该改成Integer类型,否则CSZ.Substring(FourthC)会因为参数类型不匹配报错:
    Dim FourthC As Integer = CSZ.Length() - 4
    
  • 重复执行了strAdress = CStr(txtadress.Text),可以删掉其中一行,避免冗余。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 06:26:24