Unable to cast String to DateTime

1k views Asked by At

I've following TextBox with ajax calender extender and on TextChanged event I am calling "txtFromDate_TextChanged" function.

asp code:

<asp:TextBox ID="txtFromDate" runat="server" AutoPostBack="True" 
                            ontextchanged="txtFromDate_TextChanged"></asp:TextBox>
  asp:CalendarExtender ID="txtFromDate_CalendarExtender" Format="dd/MM/yyyy" runat="server" Enabled="True"
                            TargetControlID="txtFromDate">
                        </asp:CalendarExtender>

c# code:

protected void txtFromDate_TextChanged(object sender, EventArgs e)
{
  if (txtFromDate.Text != "")
  {
    DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);
    Query = Query + "And   CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, ord_del_date))) >= '" + fromdate.ToString("yyyy'-'MM'-'dd") + "'";

  }
}

This code is working all fine when i debug through visual studio and even when I host the site on my local IIS server. The problem is that when I host the site on my online hosting server and when I pick a date from calender and calls a textchanged event it gives following error:

Error:

String was not recognized as a valid DateTime.

I know it is giving error because of line:

DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);

But I am not finding anything wrong in this code. This code is working perfectly fine from visual studio or when hosted on IIS but I am totally confused why it isn't working when hosted on hosting server. I am totally confused. Please help me out.

4

There are 4 answers

0
Rhushikesh On BEST ANSWER
DateTime fromdate = DateTime.ParseExact(txtToDate.Text, "dd/MM/yyyy", null);

Query = Query + "And   CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, ord_del_date))) >= '" + fromdate.ToString("yyyy'-'MM'-'dd") + "'";
0
Ankur On

Try changing date format in aspx to

dd-MMM-yyyy (if you want month)

or

dd-MM-yyyy (if you want only month)
0
sangram parmar On

TRy this:

IFormatProvider provider = new System.Globalization.CultureInfo("gu-IN", true);
DateTime dtime = DateTime.Parse(txtFromDate.Text, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
0
senthilkumar2185 On
fromdate.ToString("yyyy'-'MM'-'dd")

change this format it is working

fromdate.ToString("yyyy-MM-dd")