kri*_*ieg 1 c# datetime datagridview datetimepicker winforms
我一直在寻找这个答案一段时间:
我有一个 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()
Run Code Online (Sandbox Code Playgroud)
这是我的 DateTimePicker 的格式:
ReservationDateTimePicker.Format = DateTimePickerFormat.Custom;
ReservationDateTimePicker.CustomFormat = "dd/MM/yyyy - hh:mm tt";
Run Code Online (Sandbox Code Playgroud)
这是日期在 DataGridView 中的外观:

关于如何将 DataGridView 的 Date 值转换为适合具有该格式的 DateTimePicker 的 DateTime 的任何想法?
将 datagridview 单元格值转换为日期时间的最佳方法是使用 convert 函数。如果您通过 dataGridView 使用循环。例如说for循环。
for(int i=0; i<dataGridView1.Rows.Count; i++)
{
DateTime date = Convert.ToDateTime(dataGridView1.Rows[i].Cells[1].Value.ToString());
}
Run Code Online (Sandbox Code Playgroud)
如果您没有通过 dataGridView 使用任何循环,那么只需使用以下代码即可。
DateTime date2 = Convert.ToDateTime(dataGridView1.CurrentRow.Cells[0].Value.ToString());
Run Code Online (Sandbox Code Playgroud)
如果您使用的是 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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17064 次 |
| 最近记录: |