【发布时间】:2020-02-05 12:20:17
【问题描述】:
我一直在为我的大学做一个项目,我必须为服务员创建一个可以在手持计算机上使用的程序。我创建了另一个表单,用户可以在其中输入表号,但是当输入到文本框为空后会发生错误。
System.InvalidCastException '从字符串 "" 到类型 'double' 的转换无效'
Public Module GlobalVariables
Public TableNumber As Integer
End Module
Public Class Form1
Private Sub TableNumber_TableNumber_TextChanged(sender As Object, e As EventArgs) Handles TableNumber_TableNumber.TextChanged
If TableNumber_TableNumber.Text > 25 Then
TableNumber_Error.Visible = True
If TableNumber_TableNumber.Text < 1 Then
TableNumber_Error.Visible = True
End If
End If
End Sub
End Class
这是我第一次在 Visual Basic 中编码,我很困惑,因为我没有将任何东西转换为双精度。
【问题讨论】:
-
您需要做的是设置
Option Strict On,让Visual Studio 向您展示问题并提出解决方案。 -
然后决定当
TableNumber_TableNumberTextBox 中没有任何内容时你想要发生什么。您可以使用Int32.TryParse 来检查输入的内容是否实际上是一个数字,而不是像“是”这样的东西。 -
我有 Option Strict,在我设计代码时它没有任何建议。
-
如果 Option Strict 为 On,则表明
If TableNumber_TableNumber.Text > 25 Then行有问题。为了更加确定,您可以在所有代码之前的第一行输入Option Strict On。 -
当然你没有有 Option Strict On。
TableNumber_TableNumber.Text > 25将字符串与数值进行比较,而 Option Strict On 则无法做到这一点。此外,当您处理TextChanged事件时,您会检查 Text 属性是否返回一个空/空字符串(例如,if string.IsNullOrEmpty(TableNumber_TableNumber.Text) then return或IsNullOrWhitespace等作为最小验证)
标签: vb.net