Skip to main content
 首页 » 编程设计

c#之将 DataGridView 单元格值转换为 DateTime

2024年02月06日8qq号

我一直在寻找这个答案:

我有一个 datagridview,它有一个带有日期的单元格,我需要将该单元格中的值设为 DateTime 值,该值可以与我的 DateTimePicker 一起使用

到目前为止我已经这样做了,但它没有用,它给了我一个 System.FormatException(显然它不能将字符串识别为 DateTime,这听起来是正确的)

这是有问题的代码:

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

我的 DateTimePicker 是这样格式化的:

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

这是日期在 DataGridView 中的样子:

关于如何将 DataGridView 的日期值转换为适合具有该格式的 DateTimePicker 的 DateTime,有什么想法吗?

请您参考如下方法:

将 datagridview 单元格值转换为日期时间的最佳方法是使用转换函数。 如果您正在通过 dataGridView 使用循环。例如说 for 循环。

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

如果您没有在 dataGridView 中使用任何循环,则只需使用以下代码。

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

如果您正在使用 dataGridView1 CellContent Click 事件,请使用以下代码。

private void grd_All_Degrees_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
  DateTime date3 = Convert.ToDateTime(grd_All_Degrees.Rows[e.RowIndex].Cells[0].Value.ToString());      
}