Reputation: 257
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:
Any ideas on how I can convert the DataGridView's Date value into a DateTime that will fit into a DateTimePicker with that formaT?
Upvotes: 1
Views: 22303
Reputation: 409
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());
}
Upvotes: 5
Reputation: 300529
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.
Upvotes: 0