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

Igor
  • 60,821
  • 10
  • 100
  • 175
Karl
  • 19
  • 5
  • 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` – Pikoh Apr 17 '17 at 13:36
  • 1
    Possible duplicate of [Convert string to datetime Using C#](http://stackoverflow.com/questions/1989342/convert-string-to-datetime-using-c-sharp) – Heretic Monkey Apr 17 '17 at 13:42

2 Answers2

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.

Graham
  • 7,431
  • 18
  • 59
  • 84
Igor
  • 60,821
  • 10
  • 100
  • 175
-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;
CDspace
  • 2,639
  • 18
  • 30
  • 36
user7415073
  • 290
  • 4
  • 22