-3

I have a column in my database with dates stored as string in the following format:

  • 2/6/2018
  • 5/9/2018

In my winform, I am using a DataGridView, which is linked to a DataSet.

On a cell_click event I want to extract the string from the respective column in the datagridview (studentstudentbirthdateDataGridViewTextBoxColumn) and parse it into a DateTimePicker element.

This is my code:

string dateTimeString = row.Cells["studentstudentbirthdateDataGridViewTextBoxColumn"].Value.ToString();
dateStudentBirthdate.Value = DateTime.ParseExact("dd/MM/yyyy", dateTimeString, CultureInfo.InvariantCulture);

However, when I initiate the event I get the following error:

String was not recognized as a valid `DateTime`.

Any clues what is it that I am getting wrong?

SᴇM
  • 7,024
  • 3
  • 24
  • 41
Prometheus
  • 1,977
  • 3
  • 30
  • 57
  • Your format string and datetime string are swapped. – Robert Aguilar May 07 '18 at 13:04
  • Possible duplicate of [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – SᴇM May 07 '18 at 13:05
  • Another duplicate [date format issue, String was not recognized as a valid DateTime](https://stackoverflow.com/questions/16797912/date-format-issue-string-was-not-recognized-as-a-valid-datetime) – SᴇM May 07 '18 at 13:06
  • 1
    By the way, this should teach you that you should **never ever** use text fields to store dates. Use either date types or number, to store Unix timestamps – Arthur Attout May 07 '18 at 13:07
  • 1
    If the DGV column's datatype is DateTime, most of the code us not needed. You cant cast column value to DT and since the DTP Value property is `DateTime` no heroics needed to assign it – Ňɏssa Pøngjǣrdenlarp May 07 '18 at 14:51

3 Answers3

1

your sample data contain 1 digit for day and 1 for month, where as on your parse format you specify to digits for each. Try:

 DateTime.ParseExact("d/M/yyyy",
                     dateTimeString, CultureInfo.InvariantCulture);
apomene
  • 14,282
  • 9
  • 46
  • 72
0

According to your comment:

Yes, but the data can also contain double digit days. 20/05/2016 for example.

DateTime.ParseExact have one more overload ParseExact(String, String[], IFormatProvider, DateTimeStyles) which will allow you to provide multiple parse formats. For example:

string dateString = "2/6/2018"; //or "20/05/2016"
string[] formats = { "d/M/yyyy", "dd/MM/yyyy" };
DateTime dt = DateTime.ParseExact(dateString, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);

Fiddle Example

SᴇM
  • 7,024
  • 3
  • 24
  • 41
0

The soluton is simple.. don't use ParseExact:

DateTime dateTime = DateTime.Parse("2/6/2018");
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32