Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#3.5
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.
 
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
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
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 11-Jan-11 23:24pm
Edited 11-Jan-11 23:32pm
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  
Comments
Dalek Dave at 12-Jan-11 5:03am
   
Well Said.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
Comments
Dalek Dave at 12-Jan-11 5:03am
   
Good Answer.
Member 8569972 at 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);
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 4

In this what I should pass in format and Provider
 
Pls explain through example.
 
Pls send me C# code.
 
I really need this .
  Permalink  
Comments
Estys at 12-Jan-11 6:09am
   
See example in link : http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
You should use "Add Comment" instead of "Answer" if you need clarification about something.
Cheers
Manjula.c.m at 20-Sep-11 7:19am
   
Pls explain through example.

Pls send me C# code.

I really need this .
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
 
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LinkButton1.Visible = false;
Image3.Visible = false;
Image4.Visible = false;
Image6.Visible = false;
Image7.Visible = false;
Label37.Visible = false;
int i, n = 2000, d = 32, r = 61, j = 2012, k = 2015, l = 2012;
for (i = 2000; i < j; i++)
{
DropDownList5.Items.Add(Convert.ToString(i));
}
for (i = 2003; i < k; i++)
{
DropDownList6.Items.Add(Convert.ToString(i));
}
for (i = 2003; i < l; i++)
{
DropDownList7.Items.Add(Convert.ToString(i));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
String s;
s = DropDownList1.SelectedItem.Text;
switch (s)
{
case "Male":
Image4.Visible = true;
break;
case "Female":
Image3.Visible = true;
break;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
AppSettingsReader asr = new AppSettingsReader();
string conn = asr.GetValue("ConnectionString", typeof(System.String)).ToString();
try
{
SqlConnection sc=new SqlConnection(conn);
sc.Open();
string str;
str = TextBox3.Text.ToString();
DateTime dt;
dt = DateTime.Now;
dt = Convert.ToDateTime(str);
string role = "user";
string cmdstr1 = "INSERT INTO login VALUES('" + TextBox4.Text + "','" + TextBox5.Text + "','" + DropDownList9.SelectedItem.Value + "','" + TextBox15.Text + "','" + TextBox7.Text + "','" + dt + "','" + role + "')";
SqlCommand cmd1 = new SqlCommand(cmdstr1, sc);

string cmdstr = "INSERT INTO register VALUES('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DropDownList1.SelectedItem.Value + "','" + dt + "','" + DropDownList2.SelectedItem.Value + "','" + DropDownList3.SelectedItem.Value + "','" + DropDownList4.SelectedItem.Value + "','" + DropDownList5.SelectedItem.Value + "','" + DropDownList6.SelectedItem.Value + "','" + DropDownList7.SelectedItem.Value + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox7.Text + "','" + TextBox9.Text + "','" + TextBox14.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + DropDownList8.SelectedItem.Value + "','" + TextBox12.Text + "','" + TextBox13.Text + "')";
SqlCommand cmd = new SqlCommand(cmdstr, sc);
string cmdstr2 = "INSERT INTO userdetails VALUES('" + TextBox4.Text + "','" + null + "','" + null + "','" + null + "','" + null + "','" + null + "','" + null + "')";
SqlCommand cmd2 = new SqlCommand(cmdstr2, sc);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
cmd2.ExecuteNonQuery();
string cmdstr3 = "INSERT INTO birthday VALUES('" + TextBox4.Text + "','" + dt.ToString("d") + "','" + null + "','" + null + "','" + DropDownList3.SelectedItem.Value + "','" + DropDownList4.SelectedItem.Value + "','" + null + "','" + null + "')";
SqlCommand cmd3 = new SqlCommand(cmdstr3, sc);
cmd3.ExecuteNonQuery();
sc.Close();
Response.Redirect("RegSuccess.aspx");
}
catch (Exception ex)
{
//Console.WriteLine(ex.ToString());
Response.Write(ex.Message);
Label37.Visible = true;
Label37.Text = ex.ToString();
 
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
AppSettingsReader asr = new AppSettingsReader();
string conn = asr.GetValue("ConnectionString", typeof(System.String)).ToString();
SqlConnection sc = new SqlConnection(conn);
sc.Open();
string msdr = "select * from register where username= '" + TextBox4.Text + "' ";
SqlDataAdapter adpt2 = new SqlDataAdapter(msdr, conn);
DataSet ds2 = new DataSet();
adpt2.Fill(ds2, "USER");
DataTable dt2 = ds2.Tables["USER"];
if (dt2.Rows.Count >0)
{
Image7.Visible = true;
}
else
{
Image6.Visible = true;
}
sc.Close();
}
protected void TextBox5_TextChanged(object sender, EventArgs e)
{
 

 
}
protected void DropDownList7_SelectedIndexChanged(object sender, EventArgs e)
{
 
}
}
 

 
// System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at System.Convert.ToDateTime(String value) at Registration.Button1_Click(Object sender, EventArgs e) in c:\Users\PC\Desktop\website\socil\Classmates Project Final-7-6-2010\Registration.aspx.cs:line 68
  Permalink  
Comments
CHill60 at 12-Feb-15 7:59am
   
Is this meant to be a solution? The question was answered 4 years ago.
If you have a question of your own then post it as a question

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



Advertise | Privacy | Mobile
Web04 | 2.8.150326.1 | Last Updated 12 Feb 2015
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100