简体   繁体   中英

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.'

Ihave a windows form application C# , when i click on edit on a row, the date in the datagridview have to go into the datetimepicker, but when the day of this date begin's with 0, i obtain this error:

System.FormatException: 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.' my code is :

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

the string ddn looks like 02-May-95, the day begins with 0, and that causes a problem when i try to put ddn in the datetimepicker.

I tried many times to solve this problem, and no solution works!

See the pictures:

c# app code and error

You should take a look at the CustomFormat property and verify it fits the Text you are trying to set.

From 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.

If the column in the DataGrid is already a DateTime then there's no need to use strings, simply assign it to the picker:

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

Another option as per the comments is to use DateTime.ParseExact
For example:

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

Or in your case exactly:

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

The error message is more important that the format of the string itself.

"There is an unknown word starting at index 0"

is not a normal incompatible date format error message. Have a look at dnn before it is assigned to the DatePicker , to show what is at index 0 and confirm that you are assigning a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM