Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
Want to save datetimepicker value in database and datatype is date. while I am saving this value the error occurred. The error is"Conversion failed when converting date and/or time from character string.". How to solve this error.

SqlCommand com = new SqlCommand("insert into Test values('" + dateTimePicker1.Value.Date + "')", con);

Anyone help me.
Thanking you
Posted
Updated 26-Aug-15 1:15am
v2
Comments
Suvendu Shekhar Giri 26-Aug-15 6:13am    
Post the relevant code.
Mekalamani 26-Aug-15 6:21am    
SqlCommand com = new SqlCommand("insert into Test values('" + dateTimePicker1.Value.Date + "')", con);
Richard MacCutchan 26-Aug-15 6:50am    
You should save the value as a DateTime type and then insert it into your database. Also do not use string concatenation in SQL; use proper parameterised queries.
Sinisa Hajnal 26-Aug-15 7:17am    
Use parametrized query as ziad and Mekalamani suggest. But add additional check to see if the date is set before you send it to the database.

NEVER concatenate user input directly into SQL. Google "SQL Injection" to find out why.

1 solution

Try this

SqlCommand com = new SqlCommand("insert into Test values(@DtValue, con);
com.Parameters.AddWithValue("DtValue",dateTimePicker1.Value.Date);
 
Share this answer
 

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