Rick
Rick

Reputation: 37

Filter Date Range - from Date to Date - DataTable

I am relatively new to C#, but learning. I have a DGV with a table called Returns and the Date column is DateOfEntry. I thought setting this up would be rather simple..but I keep getting Operand errors and I am not sure why. I have researched this to no end and have tried various approaches with no luck. Below is the code I am using, could someone explain to me what I may be doing wrong?

Using and Access .mdb file as a DB

returnsBindingSource.Filter = ("Select * from Returns where DateOfEntry 
between '"+dateTimePicker1.Value.ToString()+"' and  
'"+dateTimePicker2.Value.ToString()+"'");

Upvotes: 1

Views: 615

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You should not assign a select statement as BindingSource.Filter. It needs a string filter expression which follows these expression syntax.

In fact it's a client-side filter mechanism which doesn't need a round-trip to data base server to filter data. When you assign a filter expression to BindingSource.Filter, the filter will apply on underlying data source, for example on your DataTable.

So you should load data in Load event of the form, then apply the filter on loaded data in Click event of a filter button for example.

Date values should be enclosed within # signs. For example:

returnsBindingSource.Filter =
    String.Format("DateOfEntry >= #{0:yyyy/MM/dd}# AND DateOfEntry <= #{1:yyyy/MM/dd}#",
    dateTimePicker1.Value,
    dateTimePicker2.Value);

Upvotes: 1

Related Questions