Conversion from string {0} to type 'Date' is not valid.
Recently on a web page that was developed in ASP.NET 2.0 with Visual Studio 2008 (code name Orcas) Beta 2, I got a conversion error from Internet Explorer.
I think conversion from string to date failed in IE because I use AjaxToolkit Extensions such as UpdatePanel.
I believe the conversion error should also occur before I use the Ajax extension in the project, but the same code block was not informed to cause problem in the application.
The error is :
Windows Internet Explorer
Conversion from string "18/05/2006 08:38" to type 'Date' is not valid.
You can see the error message that is displayed by the IE below
After reviewing the code, I found the code block that is triggering the error in the ItemDataBound event of the datagrid object that I placed in the UpdatePanel.
It is a surprise that I used the following code statement in the codebehind
And I know that conversion from text or string to date will definitely fail if you are especially working with cultures that datetime formats differ from US datetime format.
For instance Deutch, Turkish or Russian datetime formats are like DD.MM.YYYY and this is different than MM.DD.YYYY datetime format.
So before converting or casting a string or text value into a datetime value, I had to know what is the culture of the string that is displaying datetime information. Culture or the format of the string which displays date-time should be considered for a successfull or correct
datetime conversion from string.
Since my web site application is a localized and multi cultured application I'm using culture information of the user and the country where application is deployed.
And the format or the culture which keeps the datetime format in it can be retrieved from
CultureInfo.CurrentCulture class.
So, before casting or converting string to date to get the System.IFormatProvider culture specific format information I used the following code block:
currCul.DateTimeFormat is the IFormatProvider which I need for converting string to datetime.
One important note I used the DateTime.TryParse sub for the conversion or casting from string to date in order to use the
format provider.
Here is the finalized vb.net statements I used in the ItemDataBound event.
DateTime.TryParse(e.Item.Cells(GRDCOLIND_UPDATEDON).Text, currCul.DateTimeFormat, System.Globalization.DateTimeStyles.None, _UPDATEDON) is the statement that saves me :) this time.
DateTime.TryParse gets a string parameter which displays string representation of datetime value. One other parameter that I supplied to DateTime.TryParse is the IFormatProvider object which represents DateTimeFormat of the related Culture.
And the last important parameter is the datetime variable which DateTime.TryParse parses text value as datetime and stores in it.