krieg krieg - 1 month ago 12x
C# Question

Convert a DataGridView Cell Value into a DateTime

I've been searching for some time now for this answer:

I've got a datagridview that has a cell with dates, and I need to make the value in that cell a DateTime value that can go with my DateTimePicker

So far I've done this, but it's not working, it gives me a System.FormatException (apparently it can't recognize the string as a DateTime, which sounds about right)

This is the code in question:

int index = ReservationDataGridView.SelectedRows[0].Index;
string date = ReservationDataGridView[0, 1].Value.ToString();
DateTime test = DateTime.ParseExact(date, "dd/MM/yyyy - hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);


This is how my DateTimePicker is formatted:

ReservationDateTimePicker.Format = DateTimePickerFormat.Custom;
ReservationDateTimePicker.CustomFormat = "dd/MM/yyyy - hh:mm tt";

And this is how the dates look in the DataGridView:


Any ideas on how I can convert the DataGridView's Date value into a DateTime that will fit into a DateTimePicker with that formaT?


Rather than take the string representation of the DateTime value from the DataGridview cell, instead retrieve the actual DateTime value from the DataDridview's datasource.