The conversion of a varchar data type to a datetime data type resulted in an out-of-range value error
I\'m trying to enter data into my table using a form, the date
Basically, you shouldn't be passing the DateTime
values as strings in your SQL at all. Use parameterized SQL, and just set the parameter value directly. You should always use parameterized SQL as far as possible:
Additionally, your exception handling is pointlessly complex. Just use a using
statement, and let the SqlException
bubble up directly - why bother wrapping it in a vanilla Exception
?
sql = "INSERT INTO Project (ProjectId, Name, ExpectedStartDate, ExpectedEndDate, CustomerId, AdministratorId)";
sql += String.Format("VALUES('{0}', '{1}', '{2}', '{3}', {4}, {5})", projectId, name, startDate.toString("dd-MMM-yyyy"), endDate.toString("dd-MMM-yyyy"), customerId, administratorId);
A suggestion : why are you using Insert
statement in your code? You can have a stored procedure instead.
You can do sqldatetime conversion like sqldatetime
var sqlFormattedDate = myDateTime.Date.ToString("yyyy-MM-dd HH:mm:ss");