I have a textbox with a calendar extender.
The format should be like this:
<add key="DateFormat" value="dd/MM/yyyy"/>
I have the following on my aspx markup
<asp:TextBox ID="txt" runat="server"
meta:resourcekey="txt" MaxLength="150" HtmlEncode="False"></asp:TextBox>
<ajaxToolkit:CalendarExtender runat="server"
TargetControlID="txt"
PopupButtonID="Image1" Format="<%$Appsettings:DateFormat%>" />
WHen I try to use it in a property like this:
datett= DateTime.Parse(txt.Text),
It says FormatException.
I debugged and also tried Convert.ToDatetime, same exception raised.
The text I am testing is 30/05/2015
which according to my format in my web.config should work fine.
update1 I use the following code to change the language and culture of my page based on user selection, maybe this is why its failing,
I see many answers, the 2nd question would be, how to get the current culture?
/// <summary>
/// Handles the AcquireRequestState event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create culture info object
/*var ci = new CultureInfo(Session["Language"].ToString());
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);*/
System.Web.UI.Page p = (System.Web.HttpContext.Current.Handler as System.Web.UI.Page);
if (p != null)
{
p.UICulture = p.Culture = new CultureInfo((string)Session["Language"]).Name;
}
}
The solution is to adjust the culture property on your IIS if you hosting your website on it, or if you working locally you should use the following code when parsing your date:
If that worked for you you could set this culture as the default on your master page.
Another solution is to split the date text and put each splited part into it's according date part like this for instance for this date "30/05/2015":
You should add the formatter when you are parsing. Adding the DateFormat key to you web.config will not do anything by it self.
In all cases it is better to use TryParse to handle any formatting errors.
You could use
DateTime.ParseExact
and/or pass the culture explicitely:Edit: If you're dynamically changing the culture and storing it in Session, this should work:
Try using
or