Question

i am using vb.net here is my code to filter bindingsource i get this erro Syntax error: Missing operand before 'And' operator.

Private Function SetFilter() As String
    Dim datee As String = String.Format("datee >= #{0:M/dd/yyyy}# AND datee <= #{1:M/dd/yyyy}#", _
                              DateTimePicker1.Value, _
                              DateTimePicker2.Value)
    Dim client As String = If((TextBox1.Text.Length > 0), String.Format("[client] LIKE '%{0}%'", TextBox1.Text), "")
    Dim ref As String = If((TextBox2.Text.Length > 0), String.Format("[REF] LIKE '%{0}%'", TextBox2.Text), "")

    Return String.Format("{0} AND {1} AND {2}", datee, client, ref)
End Function


Private Sub DateTimePicker1_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker1.ValueChanged
    SalesBindingSource.Filter = SetFilter()
End Sub

Private Sub DateTimePicker2_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker2.ValueChanged
    'error here
    SalesBindingSource.Filter = SetFilter()
End Sub

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
    SalesBindingSource.Filter = SetFilter()
End Sub

Private Sub TextBox2_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox2.TextChanged
    SalesBindingSource.Filter = SetFilter()
End Sub
Was it helpful?

Solution

I suggest to replace your filter creating method with a more secure way to handle the content of the two textboxes and the situation in which one or both textboxes are empty

Dim client As String = If((TextBox1.Text.Length > 0), _
             String.Format(" AND [client] LIKE '%{0}%'", TextBox1.Text.Replace("'", "''")),"")
Dim ref As String = If((TextBox2.Text.Length > 0), _
             String.Format(" AND [REF] LIKE '%{0}%'", TextBox2.Text.Replace("'", "''"), "")

Return String.Format("{0} {1} {2}", datee, client, ref)

The replace call double a single quote inserted by your user in the textbox, the AND is directly inserted in the string for client and for ref, otherwise you get an invalid sql if one or both textboxes are empty

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top