1

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);

MessageBox.Show(test.ToString()

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:

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
krieg
  • 259
  • 1
  • 3
  • 19
  • I'm sorry, but I don't get what you mean -- edit: Oh, that's because the datasource is a database and the user would choose from the datagridview, although now that you say so I could get it off the database. – krieg Oct 19 '14 at 23:31
  • I went a bit ahead of myself saying that, you're right, I can get the date very easily off the database through Entity Framework. If you want the rep, or the official recognition just post it as an answer and I'll check it. Thank you so much! – krieg Oct 19 '14 at 23:41

2 Answers2

5

The Best way to convert a datagridview cell value to datetime is by using convert function. If You are using a loop through a dataGridView. For instance say for Loop.

for(int i=0; i<dataGridView1.Rows.Count; i++)
{
  DateTime date =  Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value.ToString());   
}

If you are not using any loop through dataGridView than simply use the following code.

DateTime date2 = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[0].Value.ToString());

If You are using dataGridView1 CellContent Click event than use the following Code.

private void grd_All_Degrees_CellClick(object sender, DataGridViewCellEventArgs e)
{
  DateTime date3 = Convert.ToDateTime(grd_All_Degrees.Rows[e.RowIndex].Cells[0].Value.ToString());     
}
Frits
  • 7,341
  • 10
  • 42
  • 60
Muhammad Abbas
  • 389
  • 6
  • 15
0

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.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541