how to solve this error: System.FormatException: 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.'

how to solve this error: System.FormatException: 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.'

我有一个 windows 表单应用程序 C#,当我单击一行上的编辑时,datagridview 中的日期必须进入 datetimepicker,但是当此日期的日期以 0 开头时,我得到此错误:

System.FormatException: 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.' 我的代码是:

int currentRow = int.Parse(e.RowIndex.ToString());
string ddn = dgv_patients[9, currentRow].Value.ToString();
dateTimePicker_ddn.Text = ddn;

字符串 ddn 看起来像 02-May-95,日期从 0 开始,当我尝试将 ddn 放入日期时间选择器时,这会导致问题。

我尝试了很多次解决这个问题,都没有解决办法!

看图片:

c# app code and error

您应该查看 CustomFormat 属性 并确认它适合您尝试设置的文本。

来自 MSDN - DateTimePicker.Text Property:

The string returned by this property is equivalent to the Value property with the appropriate formatting or custom formatting applied. For example, if the Value property is set to 06/01/2001 12:00:00 AM while the CustomFormat property is set to "dddd, MMMM dd, yyyy", the Text property value is "Friday, June 01, 2001".
When setting this property, the string must be convertible to an instance of the DateTime class. It is possible to define a custom format that results in a string that cannot be converted to a valid DateTime value. Because of this, the string returned from the Text property might cause an error if it is passed back to the Text property. If the string cannot be converted to a date/time value, the DateTime class throws a FormatException.

如果 DataGrid 中的列已经是 DateTime 则无需使用字符串,只需将其分配给选择器即可:

dateTimePicker_ddn.Value = (DateTime)dgv_patients[9, currentRow].Value;

根据评论的另一种选择是使用 DateTime.ParseExact
例如:

DateTime dt = DateTime.ParseExact("02-May-95", "dd-MMM-yy", CultureInfo.InvariantCulture);

或者您的情况恰好是:

dateTimePicker_ddn.Value = DateTime.ParseExact(
    dgv_patients[9, currentRow].Value.ToString(),
    "dd-MMM-yy",
    CultureInfo.InvariantCulture);

错误信息比字符串本身的格式更重要。

"There is an unknown word starting at index 0"

不是正常的不兼容日期格式错误消息。在分配给 DatePicker 之前查看 dnn,以显示索引 0 处的内容并确认您正在分配一个字符串。