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

VB.NET中字符串格式错误:文本标签报错求替代解决方案

解决Double.Parse空字符串引发的格式错误问题

问题根源很明确:点击BtnRefresh后lblDisTotal.Text被设为空字符串,调用CalculateGrandTotal时Double.Parse无法解析空值,直接抛出FormatException。给你几个实用的解决方案:

方案1:用Double.TryParse做安全解析

这是最稳妥的做法,不管输入是空值还是非数字内容,都能避免报错,还能自定义默认值(比如默认折扣为0)。修改CalculateGrandTotal方法:

Private Sub CalculateGrandTotal()
    Dim tot As Double = 0
    Dim cash As Double = 0 ' 默认折扣为0
    ' 尝试解析,失败则保持默认值
    Double.TryParse(lblDisTotal.Text, cash)
    
    For Each item As DataGridViewRow In grid.Rows
        ' 这里也建议用TryParse,避免DataGridView单元格值无效的情况
        Dim itemValue As Double = 0
        Double.TryParse(item.Cells(5).Value.ToString(), itemValue)
        tot += itemValue
    Next item
    
    lblGrandTotal.Text = (tot * (1 - cash / 100)).ToString("N2")
End Sub

方案2:刷新时设置默认值而非清空

修改BtnRefresh_Click方法,把空字符串换成"0",这样Double.Parse始终能拿到合法的数字字符串:

Private Sub BtnRefresh_Click(sender As Object, e As EventArgs) Handles BtnRefresh.Click
    lblDisTotal.Text = "0"
End Sub

方案3:先判断输入是否为空再解析

在解析前先检查lblDisTotal.Text的内容,为空则直接设默认值:

Private Sub CalculateGrandTotal()
    Dim tot As Double = 0
    Dim cash As Double = 0
    
    If Not String.IsNullOrEmpty(lblDisTotal.Text) Then
        cash = Double.Parse(lblDisTotal.Text)
    End If
    
    For Each item As DataGridViewRow In grid.Rows
        tot += Double.Parse(item.Cells(5).Value.ToString())
    Next item
    
    lblGrandTotal.Text = (tot * (1 - cash / 100)).ToString("N2")
End Sub

注意:方案3只处理了空值情况,如果用户输入了非数字内容还是会报错,所以更推荐方案1的TryParse写法,覆盖所有无效输入场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 13:35:19