-6

I am having an issue trying to convert a String to DateTime. I have tried a few things but I keep getting errors thrown up when trying to update the record.

string consentGiven = ConsentGivenDate.Text;
DateTime date1 = Convert.ToDateTime(consentGiven);
cmd.Parameters.Add(new SqlParameter("@ConsentGivenDate", date1));

if ((ConsentGivenDate.Text == "dd/mm/yyyy"))
    cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = DBNull.Value;
else
    cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = ConsentGivenDate.Text;

I have tried to add a bit of formatting in so the Date is in British format 'dd/mm/yyyy' but still can't convert it over.

What have I done wrong?

I am a real coding novice so apologies if it is something stupid....

2
  • If the column in the database is a DateTime,why do you want to insert a string? Just cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = date1 Commented Apr 17, 2017 at 13:36
  • 1
    Possible duplicate of Convert string to datetime Using C# Commented Apr 17, 2017 at 13:42

2 Answers 2

0

Always use instances of the correct type in your Sql Parameters. When a parameter corresponds with a Date or DateTime in your database schema then the corresponding .net type should be DateTime and not string.

object sqlValue = DBNull.Value;
DateTime dateConsentGiven;

if(DateTime.TryParseExact(ConsentGivenDate.Text, "dd/mm/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateConsentGiven))
    sqlValue = dateConsentGiven;
cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = sqlValue;

Also note that you are adding the same parameter multiple times in your original code in your question, Sql Server uses named parameters which means the parameter name is unique.

Sign up to request clarification or add additional context in comments.

Comments

-1
DateTime dt = DateTime dt=DateTime.ParseExact("ConsentGivenDate.Text", "dd/MM/yyyy", CultureInfo.InvariantCulture);
cmd.Parameters.Add(new SqlParameter("@ConsentGivenDate", dt));
cmd.Parameters.Add("@ConsentGivenDate", SqlDbType.DateTime).Value = DBNull.Value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.