Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am trying to insert the date into a data table using a datetimepicker, this particular column's data as been specified as datetime. When ever I run my project I get this error:

" conversion of a varchar data type to a datetime data type resulted in an out-of-range value"

Here is my sql command:

'" + Convert.ToDateTime(MyDateTimePicker.Text) + "'
Posted
Comments
Richard C Bishop 13-Feb-14 14:57pm    
Have you tried using MyDateTimePicker.Value?
1Future 13-Feb-14 15:06pm    
yessir i have indeed .. still no luck

1 solution

Stop doing that! Why use a DateTimePicker that returns a DateTime directly, and then rely on the user-dependant string it generates?

And never concatenate strings to form an SQL command - use parameterised queries instead. Concatenation can leave you wide open to SQL Injection which can damage or destroy your database - not in this case, but it's a good principle to use parameters at all times. In this case, you problem will go away as well:
C#
SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myDateColumn) VALUES (@DT)", con);
cmd.Parameters.AddWithValue("@DT", MyDateTimePicker.Value);
 
Share this answer
 
Comments
Valery Possoz 13-Feb-14 15:07pm    
2 good advices!
buy one, get one free :)
OriginalGriff 13-Feb-14 15:20pm    
Where would you like me to send the invoice? :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900