Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone ,


I got Error Failed to convert parameter value from a String to a DateTime.

In Below Scenario I got this error.

when I am doing Unit testing on my Local Machine then it is working fine.
there is no error like this on my local machine OS is windows7, but when I deploy code on Server then I got this Error , on server there is windows8 ,
IS there some culture issue due to which throw this ERROR.

Below possibilities I have checked that due to this error may be occurred :

I have check Server system datetime and my machine datetime , it is same,
changed date format like MM/DD/YYYY.

Below Code I m using :

C#
SqlParameter[] parms1 = {
            new SqlParameter("@VisitDate", SqlDbType.Date)
            };
           parms1[0].Value = DateTime.Now.Date;




but error is occurring on Server.

suggest me what I do for resolving this issue..



Thanks in advanced.


~MP
Posted
Updated 25-Aug-14 4:11am
v3
Comments
ZurdoDev 25-Aug-14 10:19am    
I would instead suggest using cmd.Parameters.AddWithValue("@paramter", value)

The syntax is much simpler and more common.

1 solution

Start off by not concatenating strings to form SQL commands: use parametrized queries instead.
Concatenating strings is very dangerous - it leave you wide open to SQL Injection which can easily damage or destroy your database.

Then check the values, and convert them in C# (when you have access to the user culture info) to an appropriate datatype and pass that through: passing valid datetime and numeric information to SQL instead of a string representation means there is no conversion for SQL to do so the error goes away.

If you pass dates as strings, then you leave SQL to guess what date format the user entered it in: was it dd/mm/yy or mm/dd/yy? Or yy/mm/dd? Or an invalid data like 32/3/1997? Or did the user type "hello"? All of these can cause SQL to throw an exception, and should be caught as early as possible and refered back to the user for correction. SQL can't do that.
 
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