'无法在System.Int32和System.String上执行'='操作。

时间:2018-11-04 11:15:48

标签: vb.net visual-studio

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

我的代码是:

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

错误是:

  

无法在System.Int32和System.String上执行'='操作。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

    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