Convert a DataGridView Cell Value into a DateTime

不羁岁月 提交于 2019-12-24 17:19:49

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/26456538/convert-a-datagridview-cell-value-into-a-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!