I'm trying to create a method that checks a date to see if it already exists within my database. However I'm getting an exception that the program is having trouble converting from varchar. Anyone able to tell me why it's doing so?
public static int CheckDate(DateTime date)
{
using (SqlConnection connection = new SqlConnection(_connectionstring))
{
int nooforders = 0;
connection.Open();
string SqlQuery = string.Format("SELECT COUNT(OrderID) AS 'OrderCount' FROM OrderTable WHERE DateofCollectionDelivery = '{0}'", date);
SqlCommand datecheck = new SqlCommand(SqlQuery, connection);
SqlDataReader sqlDataReader = datecheck.ExecuteReader();
while (sqlDataReader.Read())
{
nooforders = (int)sqlDataReader["OrderCount"];
}
connection.Close();
return nooforders;
}
}
This is the method I run and this is the exception:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The fields in the table have a datatype of datetime, so I'm unsure why it's throwing the exception.