【问题标题】:If textbox is empty or textbox is less than 3如果文本框为空或文本框小于 3
【发布时间】:2017-12-17 15:46:59
【问题描述】:

如何修复此代码?如果文本框为空,则会出现错误。

 Private Sub MetroButton1_Click(sender As Object, e As EventArgs) Handles MetroButton1.Click

    If BunifuMaterialTextbox2.Text < 3 Or BunifuMaterialTextbox2.Text = "" Then
        MsgBox("must have atleast 3 pesos profit")
    End If

End Sub

如果 textbox.text 为

【问题讨论】:

  • 首先将Option Strict On 放在代码文件的顶部,然后阅读How to Ask 并取tour
  • 使用Int32.TryParse将文本框中的String值转换为Integer

标签: vb.net visual-studio visual-studio-2017


【解决方案1】:

使用 val() :- If val(BunifuMaterialTextbox2.Text)

【讨论】:

    【解决方案2】:

    您应该打开 Option Strict。只有少数边缘情况允许某些东西成功,而没有它就不会成功,而那些通常重写起来微不足道。它所做的操作与您将要执行的操作相同,但它使可能的类型失败不太清楚。

    If BunifuMaterialTextbox2.Text < 3 Or BunifuMaterialTextbox2.Text = "" Then
    

    因为您有 Option Strict Off,所以这被视为

    If CInt(BunifuMaterialTextbox2.Text) < 3 Or BunifuMaterialTextbox2.Text = "" Then
    

    CInt 在 Nothing 上成功,返回 0,但在 "" 上失败,抛出异常。由于您使用 Or 而不是 OrElse,因此将始终评估这两个条件。此外,您的条件会首先导致异常,因此每当您的文本框为空时,它都会引发异常。

    您可以将其重写为: If BunifuMaterialTextbox2.Text = "" OrElse BunifuMaterialTextbox2.Text

    一切都会正常工作。但我真的不推荐它,因为不知道幕后发生了什么,它很脆弱。

    如果你把它重写为:

    Dim bunifuMaterial2 as Integer
    
    If not Integer.TryParse(BunifuMaterialTextbox2.Text, bunifuMaterial2) OrElse bunifuMaterial2 < 3 Then
    

    你不仅可以避免空的异常,如果他们输入一个非数字值,例如“cat”,你也可以避免异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多