【问题标题】:'Cannot perform '=' operation on System.Int32 and System.String.''无法对 System.Int32 和 System.String 执行 '=' 操作。
【发布时间】:2018-11-04 11:15:47
【问题描述】:

我使用文本框作为数字搜索,当我输入数字时它搜索但当我从框中删除它时出现错误。

我的代码是:

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles     TextBox2.TextChanged
   SpringDataBindingSource.Filter = "SerialNumber = '" + TextBox2.Text + "'"
End Sub

错误是:

无法对 System.Int32 和 System.String 执行“=”操作。

【问题讨论】:

  • 当你在VB中使用数字时,你会在它们周围加上双引号吗?不,你没有。双引号仅用于文本。 SQL 代码也是如此(Filter 属性包含一个 SQL WHERE 子句),只是您对文本使用单引号。不过,您仍然没有为数字使用任何引号。如果SerialNumber 列包含Integer 值,那么您必须将其与Integer 值进行比较,而不是Strings
  • 碰巧,您的代码是错误的,但如果您提供的值实际上是一个数字,它仍然可以工作。如果您遇到该异常,则 TextBox2 不包含数值。

标签: vb.net visual-studio


【解决方案1】:

问题是空字符串验证失败。

对于空字符串,您应该删除过滤器。

应该是这样的:

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles     TextBox2.TextChanged
   if Trim(TextBox2.Text) = "" Then
     SpringDataBindingSource.Filter = ""
   Else
     SpringDataBindingSource.Filter = "SerialNumber = '" + TextBox2.Text + "'"
   End If
End Sub

编辑

您还可以使用KeyUp 事件检查每个插入的数据:

Private Sub TextBox2_KeyUp(sender As Object, e As KeyEventArgs) Handles ComboBox1.KeyUp
    If NumericMode Then ' NumericMode is boolean and should be turnd On/Off elswhere
        If  Char.IsDigit(ChrW(e.KeyValue)) Then
           'OK
        Else
           'ERROR 
        End If
    End If
End Sub

【讨论】:

  • 您能指导我如何验证输入是否为整数吗? SerialNumber 中的数据是数字而不是文本!
  • 如果TextBox 包含非数字文本,这仍然会失败。应该使用Integer.TryParse 验证数据,或者在这里,或者更好的是,在TextBoxValidating 事件处理程序中。此外,那些单引号仍然不应该存在。你不引用数字。
  • 最好使用NumericUpDown 而不是TextBox 只获取数字。
  • #SHR 感谢您的解决方案,它有效!但是如果想在同一个文本框中按名称搜索呢?
  • @MohammadKhaled,如果你想做的不是这个问题所指定的,那么你应该发布另一个关于这个新主题的问题。当然,与往常一样,您需要先进行自己的尝试,然后向我们展示它是否以及何时不起作用。
【解决方案2】:
    Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged

    'This would work, but would consider decimals also a number
    If IsNumeric(TextBox2.Text) Then
        SpringDataBindingSource.Filter = String.Format("SerialNumber = '{0}'", TextBox2.Text)
        Return
    End If
    SpringDataBindingSource.Filter = ""
End Sub

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged

    'This would work if you want to guarantee an Int32
    Dim txtInt As Integer
    If Int32.TryParse(TextBox2.Text, TxtInt) Then
        SpringDataBindingSource.Filter = String.Format("SerialNumber = '{0}'", txtInt)
    Else
        SpringDataBindingSource.Filter = ""
    End If

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多