Dataview.RowFilter resulting in Cannot perform '=' operation on System.String and System.Int32
Dim sValue As String
sValue= DataBinder.Eval(idContainer.DataItem, "MyField").ToString.TrimEnd
'(i have a dataview dvMydataView)
dvMyDataView.RowFilter = "MyField2 = " & sValue 'Here, the "MyField2" datatype is string
If DataBinder.Eval(idContainer.DataItem, "MyField") datatype is int32 (contains a valid numeric value), then Rowfilter results in the following exception : Cannot perform '=' operation on System.String and System.Int32
Clearly, it is expecting quotes before and after sValue
On the other hand if DataBinder.Eval(idContainer.DataItem, "MyField") datatype is string, though the value contained in it is a valid integer value, then there is no exception in the row filter statement. This implies that it is not expecting quotes before and after sValue here.
What could be the reason for such a behaviour?
Solution 1:
The RowFilter
property contains what is effectively a SQL WHERE
clause. ADO.NET objects only support a very small subset of SQL syntax but it still has to be valid SQL syntax. Just as you wrap double-quotes around a String
literal in VB code, so you wrap single-quotes around a text literal in SQL code. You have no quotes around your value so it's not interpreted as a text literal.
dvMyDataView.RowFilter = $"MyField2 = '{sValue}'"
That's using string interpolation, which should be the preferred option in recent versions. You could use String.Format
or basic concatenation too.