我有一个用 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/