Laki
Laki

Reputation: 99

Selection between two date pickers

This is the code that I wrote in order to make a selection between two dates (using DateTimePicker objects)

var query = db.people.AsQueryable();

var fromDate = Convert.ToDateTime(dateTimePicker1);
var toDate = Convert.ToDateTime(dateTimePicker2);

query = query.Where(x => x.dob > fromDate && x.dob < toDate);
clan_savezaBindingSource.DataSource = query.ToList();

When I run the code the error appears saying InvalidCastException. I guess I should use something other than Convert.ToDate but I can't find a solution.

Upvotes: 1

Views: 84

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

You should use Value property of DateTimePicker. It returns selected the date as DateTime object:

var fromDate = dateTimePicker1.Value;
var toDate = dateTimePicker2.Value;

Note: DateTimePicker is not a DateTime object. And it's not convertible to DateTime. DateTimePicker is a user control which holds DateTime value and provides a lot of functionality for rendering itself and processing user input.

Further reading: Using DateTimePicker Control

Upvotes: 4

Related Questions