Click here to Skip to main content
14,087,117 members
Rate this:
Please Sign up or sign in to vote.
See more:
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:

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

The insert statement is as follows:
string query = "INSERT INTO dateTbl(recD) VALUES('" + receivedDate + "')"
Updated 4-Mar-19 23:50pm
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
Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.190518.1 | Last Updated 5 Mar 2019
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100