vb.net - 从字符串 "."到类型 'Decimal' 的转换无效

标签 vb.net

我有一个用 Visual Basic 编写的单位转换器,使用 Visual Studio 2013。该程序工作正常,直到用户的初始输入是小数点。我收到此错误消息:从字符串“.”转换输入“十进制”无效。如何让该程序接受小数点作为用户的初始输入而不导致程序崩溃?代码如下。

Private Function GetLength1(ByVal decLengthUnit1 As Decimal) As Decimal

Dim decResult1 As Decimal

If cboUnitType.SelectedItem = "Length" Then

    ' converts kilometer to...
    If cbo1.SelectedItem = "Kilometer" Then
        If cbo2.SelectedItem = "Kilometer" Then
            decResult1 = txtUnit1.Text
        ElseIf cbo2.SelectedItem = "Meter" Then
            decResult1 = (decLengthUnit1 * 1000)
        ElseIf cbo2.SelectedItem = "Centimeter" Then
            decResult1 = (decLengthUnit1 * 100000)
        ElseIf cbo2.SelectedItem = "Millimeter" Then
            decResult1 = (decLengthUnit1 * 1000000)
        ElseIf cbo2.SelectedItem = "Mile" Then
            decResult1 = (decLengthUnit1 * 0.621371191)
        ElseIf cbo2.SelectedItem = "Yard" Then
            decResult1 = (decLengthUnit1 * 1093.613297)
        ElseIf cbo2.SelectedItem = "Foot" Then
            decResult1 = (decLengthUnit1 * 3280.83989)
        ElseIf cbo2.SelectedItem = "Inch" Then
            decResult1 = (decLengthUnit1 * 39370.07868)
        End If
    End If
End If

Return decResult1.ToString().Trim("0") ' this is where I convert the data back to a string with some formatting
End Function


Private Sub txtUnit1_TextChanged(sender As Object, e As EventArgs) Handles      txtUnit1.TextChanged

    ' convert string to numeric data type
    Decimal.TryParse(txtUnit1.Text, decUnit1) ' this is where I convert user input to decimal data type

    ' handle String.Empty, or negative sign
    If txtUnit1.Text = "" OrElse txtUnit1.Text = "-" Then
        txtUnit2.Text = ""

    ElseIf cboUnitType.SelectedItem = "Length" Then
        suppressTextBox2TextChanged = True
        txtUnit2.Text = GetLength1(decUnit1)
        suppressTextBox2TextChanged = False

    End If

End Sub

最佳答案

您的函数设置为返回十进制值

Private Function GetLength1(ByVal decLengthUnit1 As Decimal) As Decimal

您可以将其更改为字符串

Private Function GetLength1(ByVal decLengthUnit1 As Decimal) As String

或者您可以更改返回

Return Ctype(decResult1.ToString().Trim("0"), Decimal)

也可能是 Decimal 需要 , 而不是 我认为这与您的文化设置有关。然后您可以更改已写入的值或执行 REPLACE

替换(decResult1.ToString().Trim("0"),".",",")

编辑

您还可以尝试更改txtUnit2.Text = GetLength1(decUnit1)

将其更改为 txtUnit2.Text = GetLength1(decUnit1).ToString().Trim("0") 并从函数内部删除 .Trim。

现在您正在修改文本框的.Text,然后使用已获得的Decimal值。

关于vb.net - 从字符串 "."到类型 'Decimal' 的转换无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306332/

相关文章:

mysql - 显示两个表中的数据并消除重复项

vb.net - 包含表单的 .NET 类库中的 SetCompatibleTextRenderingDefault

Vb.net 随机数生成器多次生成相同的数字

mysql - 从表中查找当前轮类

vb.net - Visual Basic 模块 v 单例

VB.NET - 从解决方案中的其他项目导入命名空间

mysql - 如何通过查看数据库中的角色列以经理或员工身份登录?

vb.net - 初始化 Emgu.CV 时出现异常

vb.net - 如何使用String.Format将 bool 类型转换为 "ON" "OFF"

c - c程序编译生成的.exe文件和vb程序编译生成的.exe文件有什么区别