Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello Everyone!

I got stucked in 1 error. I m trying to get the date from a MySql database table which contain Date column. Here what I did is, I have stored the date in "Date varchar(25)" into table. except this Date column, other column data got fetched successfully. I tried the following :

What I have tried:

DTP1Date.Value = (dr["Date"].ToString());

The error I m getting is : Cannot implicitly convert type 'string' to 'System.DateTime'.
Posted
Updated 14-Nov-22 1:01am
Comments
0x01AA 14-Nov-22 6:47am    
I strongly recommend you to use DATE instead of varchar(25). It will keep you away from a lot of problems in your code. And also avoid using reserved words for database fieldname, like you do it with Date

1 solution

There is but one solution: change your database.
Never store dates in NVARCHAR columns - always use DATETIME or DATE instead.
If you use the wrong column datatype it's easy to set up, and lazy to get the user data into - but it always gives total nightmares after that - because the data in your DB is not valid, or is not in a consistent format, or is in a different format from that which SQL expects.
Think about it: 10/11/12 is a valid date. But is it 10th Nov 2012, 11th Oct 2012, 12th Nov 2010, or some other value entirely? The only time you can tell is when the user inputs the value, and you use his culture to convert it to a DateTime value - as soon as it arrives in the DB it's too late because you no longer have any idea what date format he used: it could be US: MM/DD/YY, European: DD/MM/YY, or ISO / Japanese YY/MM/DD - and you don't even know that the user is using the same calendar as you so the year could be well different (the Hijri date today is Jumada Al-Awwal 3, 1438)! Or even that he didn't enter "hello, my name is Jackie" which isn't even close to a date.

So when you try to convert it to a date at a later time you are almost guaranteed to get errors because the SQL server will try to convert it using it's culture - and generally you don't even know what culture the server is set to!

Always use appropriate data types - it may be easier for your code to slam in NVARCHAR all the time, but it wastes huge amounts of effort later fixing up the holes it leaves.
 
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