rsprodftw1 rsprodftw1 - 2 months ago 11
Vb.net Question

InvalidCastException in DataView RowFilter

all! Just wanted to start off by saying that I'm new here! :)
I'm also pretty new at coding, so be gentle with me

I'm getting an InvalidCastException error when trying to apply a filter to my DataTable. The thing is, I'm trying to apply 2 filters with one being conditional.
Here's what I have:

If cbValue1.Text <> "" Then
dv.RowFilter = "Value1 " + cbValue1.Text + " " + CStr(nudValue1.Value) AndAlso If(CheckBox1.Checked = True, " AND [Value2] = 'Mon'", "")
End If


The error I get says, "Conversion from string "Value1 <= 1500" to type 'Boolean' is not valid."

If I have just this part it works just fine:

If cbValue1.Text <> "" Then
dv.RowFilter = "Value1 " + cbValue1.Text + " " + CStr(nudValue1.Value)
End If


Can someone show me what's wrong?

Answer

You're using the AndAlso Operator incorrectly. It causes this to be treated as a Boolean expression:

"Value1 " + cbValue1.Text + " " + CStr(nudValue1.Value)

Try building your RowFilter with multiple lines of code or in a different way, like this:

If cbValue1.Text <> "" Then

    Dim strRowFilterExpression As String = "Value1 " & cbValue1.Text & " " & CStr(nudValue1.Value)

    If CheckBox1.Checked Then

        strRowFilterExpression += " AND [Value2] = 'Mon'"

    End If

    dv.RowFilter =  strRowFilterExpression

End If