Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hi,
I have a masked textbox in my form where the user enters the date as dd/MM/yyyy
and then this value is inserted into a sql server table.
I'm getting the following error when the query is executed:
the conversion of a varchar data type to a datetime data type resulted in an out-of-range value


I have tried many ways and tried to look for similar issues online and tried the fixes/answers but I'm still getting the error.
The error only happens when the 'dd' entered is higher than 12 so i assume that the sql server is taking that value as the MM instead of dd.
Below is what I tried.

What I have tried:

C#
Datetime receivedDate = DateTime.ParseExact(receivedDate.Text, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);


The insert statement is as follows:
SQL
string query = "INSERT INTO dateTbl(recD) VALUES('" + receivedDate + "')"
Posted
Updated 4-Mar-19 23:50pm
Comments
Richard MacCutchan 5-Mar-19 5:47am    
why are you using a TextBox rather than a DateTimePicker?
xTMx9 5-Mar-19 6:58am    
I'm using a TextBox because there are many textboxes in the form and the user has to be fast in entering the data and switching from one to another so figured having a masked textbox would be faster.
I have not used DateTimePicker control much before so I'm not sure if text can be entered like that of a textbox or have to always choose from the calendar.
Richard MacCutchan 5-Mar-19 7:28am    
Do you really believe that the average user can type a date in your specific format faster than he/she can click on a control?
And there is an easy way to find out what features this control supports.
xTMx9 6-Mar-19 4:03am    
only a few users use that form and its faster for them that way, "Enter" from previous box, type in bunch of numbers quick then Enter, rather than clicking on a control

Don't use a concatenated string in your query. Use a parameterised query instead.

If that doesn't completely solve your problem (it should) then try formatting your date as yyyy-Mmm-dd
 
Share this answer
 
Comments
xTMx9 5-Mar-19 6:56am    
Had to edit the code and using a parameterised query solved the problem, thanks.

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