DateTime解析报错及DateTimePicker与DataGridView日期显示问题求助
Solutions to Your DateTime Parsing and Display Issues
1. Fixing the DateTime Parsing Error
The error String '12/20/2022 12:00:00 AM' was not recognized as a valid DateTime occurs because your format string doesn’t match the input structure:
- Input string format:
MM/dd/yyyy hh:mm:ss tt(month/day/year with 12-hour time) - Your code uses
dd-MM-YYYY(day-month-week-based year), which is completely mismatched.
Correct Approaches:
- If the cell value is already a DateTime: Skip string conversion entirely (most reliable):
DateTime dt = (DateTime)dgvSP.CurrentRow.Cells[5].Value; dtpQLSPnsx.Value = dt; - If the cell value is stored as a string: Use the exact format matching your input:
DateTime dt = DateTime.ParseExact( dgvSP.CurrentRow.Cells[5].Value.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture ); dtpQLSPnsx.Value = dt; - For safer parsing: Use
TryParseExactto avoid exceptions on invalid inputs:if (DateTime.TryParseExact( dgvSP.CurrentRow.Cells[5].Value.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt )) { dtpQLSPnsx.Value = dt; } else { // Handle invalid input here (e.g., show error message) }
2. Fixing DataGridView vs DateTimePicker Display Mismatch
The DataGridView only showing the date part is controlled by its column’s formatting settings. Here’s how to align the displays:
Option A: Make DataGridView show full datetime (match DateTimePicker)
Set the column’s DefaultCellStyle.Format to display the full datetime:
// Replace "DateColumnName" with your actual column name dgvSP.Columns["DateColumnName"].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";
Option B: Make DateTimePicker show only date (match DataGridView)
If you prefer the DateTimePicker to display just the date, adjust its format properties:
// Use system default short date format dtpQLSPnsx.Format = DateTimePickerFormat.Short; // Or use a custom date format (e.g., MM/dd/yyyy) dtpQLSPnsx.Format = DateTimePickerFormat.Custom; dtpQLSPnsx.CustomFormat = "MM/dd/yyyy";
Note: Converting the DateTimePicker’s value to a date-only type won’t change how the DataGridView displays it—you need to adjust the grid’s column formatting directly.
内容的提问来源于stack exchange,提问作者Adudu123
相关产品推荐
相关产品推荐

