I'm working on a C# project where you can make reservations.
Now I have to search on a date between the Start and End date from a Microsoft SQL server database selected with a DateTimePicker.
I did the same with searching on name but for some reason it doesn't work with the date.
This is the code I used:
private void btnZoekDatum_Click(object sender, EventArgs e)
{
DateTime zoekOpdracht = dtpZoekDatum.Value;
//MessageBox.Show(zoekOpdracht);
/*if (zoekOpdracht != "")
{*/
con.Open();
/*try
{*/
cmd = "SELECT * FROM reserveringen WHERE Startdatum >= @datum AND Einddatum <= @datum";
command = new SqlCommand(cmd, con);
SqlDataAdapter da = new SqlDataAdapter(command);
command.Parameters.Add(new SqlParameter("@datum", SqlDbType.DateTime) { Value = dtpZoekDatum.Value });
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
dgvReserveringen.DataSource = dt;
dt.Dispose();
da.Dispose();
//con.Close();
}
else
{
MessageBox.Show("Er is helaas geen reservering gevonden.");
con.Close();
}
/*}
catch (Exception)
{
MessageBox.Show("Er is helaas geen reservering gevonden.");
//con.Close();
}*/
/*}
else
{
MessageBox.Show("Voer a.u.b. een zoekopdracht in.");
}*/
}
Now if I choose a date and press Search, I get the following error (the error shown by da.Fill(dt);
):
System.Data.SqlClient.SqlException: 'The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.'
I already tried some things with converting but then I still got an error. Maybe my SQL query is wrong...
So does someone know what the problem is and how I can fix this?
Thanks in advance!