Click here to Skip to main content
15,879,348 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
My query is when I created web setup of my web application. And then run it on my computer it runs fine but when I enter fromdate(dd/MM/yyyy) and todate(dd/MM/yyyy) in textbox and then submit it, then it gives an error that string was not recognized as a valid datetime.

I want to enter date format like dd/MM/yyyy in textbox and save yyyy-MM-dd in database.

The error page is shown below.


Server Error in '/DT' Application.
--------------------------------------------------------------------------------

String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

C#
Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error: 


Line 23:         //DateTime dt1 = Convert.ToDateTime(TextBox1.Text.Trim());
Line 24:         //DateTime dt2 = Convert.ToDateTime(TextBox2.Text.Trim());
Line 25:         string dt1 = Convert.ToDateTime(TextBox1.Text.Trim()).ToString();
Line 26:         string dt2 = Convert.ToDateTime(TextBox2.Text.Trim()).ToString();
Line 27:         SqlConnection conn = new SqlConnection("Data Source=MAX9;Initial Catalog=Leave;User ID=sa;pwd=;");
 

Source File: c:\Inetpub\wwwroot\DT\Default2.aspx.cs    Line: 25 

Stack Trace: 


[FormatException: String was not recognized as a valid DateTime.]
   System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) +2838082
   System.Convert.ToDateTime(String value) +98
   Default2.Button1_Click(Object sender, EventArgs e) in c:\Inetpub\wwwroot\DT\Default2.aspx.cs:25
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.3615; ASP.NET Version:2.0.50727.3618 


Source Code and stored procedure which I used on Send button
C#
protected void Button1_Click(object sender, EventArgs e)
{
        
        string dt1 =Convert.ToDateTime(TextBox1.Text.Trim()).ToString();
        string dt2 =Convert.ToDateTime(TextBox2.Text.Trim()).ToString();
        SqlConnection conn = new SqlConnection("Data Source=MAX9;Initial Catalog=Leave;User ID=sa;pwd=;");
        SqlCommand cmd = new SqlCommand("insert_testtable", conn);
        conn.Open();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@FromDate", SqlDbType.DateTime).Value = dt1;
        cmd.Parameters.Add("@ToDate", SqlDbType.DateTime).Value = dt2;
      

        try
        {
            cmd.ExecuteNonQuery();
            lblMessage.Text = "Record inserted successfully";
        }
        catch (Exception ex)
        {
            throw ex;
        }
        conn.Close();


         }
}


Stored Procedure
SQL
CREATE PROCEDURE [dbo].[insert_testtable]
@FromDate datetime,
@ToDate datetime
 AS
insert into testtable values (@FromDate,@ToDate)
GO


Please solve my query as soon as possible. Thanks in advance.
Posted
Updated 27-Apr-19 0:57am
v3

you should use DateTime.Parse(String, IFormatProvider) :
http://msdn.microsoft.com/en-us/library/kc8s65zs.aspx[^]

the line
cmd.Parameters.Add("@FromDate", SqlDbType.DateTime).Value = dt1;


is plain wrong, don't use a string, use a datetime.

Cheers
 
Share this answer
 
Comments
Dalek Dave 12-Jan-11 5:03am    
Well Said.
Use the following code:

string format = "dd/MM/yyyy"; 
DateTime dt = DateTime.ParseExact(dateString, format, provider);


If you expect the user to give input in format "MM/dd/yyyy", you need to use the following code:

string format = "MM/dd/yyyy"; 
DateTime dt = DateTime.ParseExact(dateString, format, provider);


You don't need to worry about in which format the DateTime object is being saved in the Database, as long as only your application retrieves the same DateTime data.
 
Share this answer
 
Comments
Dalek Dave 12-Jan-11 5:03am    
Good Answer.
Member 8569972 18-Jan-12 0:58am    
Hello I am using your following code but it gives error for provider, so please can you tell me what is provider?

string format = "dd/MM/yyyy";
DateTime dt = DateTime.ParseExact(dateString, format, provider);

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900