• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5443
  • Last Modified:

Conversion failed when converting datetime from character string.

ms visual studio 2005
sql erver 2005

I get the following error when trying to insert into db from web app

have tried....
txtrequireddate.Text.ToString("dd-MMM-yyyy ")
reqrddate = Convert.ToDateTime(txtrequireddate.Text)
reqrddate= CDate(txtrequireddate.Text)


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

Conversion failed when converting datetime from character string.
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.Data.SqlClient.SqlException: Conversion failed when converting datetime from character string.

Source Error:


Line 94:                 "values ('" & username & "','" & reqrddate & "','" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"
Line 95:                 Dim myCommand As New SqlCommand(sql, myConnection)
Line 96:                 myCommand.ExecuteNonQuery()<--- highlighted
Line 97:             ElseIf (j = 0) Then
Line 98:                 lblnoitem.Visible = True
 

Source File: C:\Inetpub\loans\MemberPages\Request.aspx.vb    Line: 96

Stack Trace:


[SqlException (0x80131904): Conversion failed when converting datetime from character string.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +857242
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +734854
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1838
   System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async) +192
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +380
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +135
   Request.Button1_Click(Object sender, EventArgs e) in C:\Inetpub\loans\MemberPages\Request.aspx.vb:96
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5102

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
0
deNZity
Asked:
deNZity
  • 13
  • 9
1 Solution
 
HillwaaaCommented:
Hi deNZity,

A couple of quick things:

(1) try txtrequireddate.Text = txtrequireddate.Text.ToString("dd-MMM-yyyy ")
(2) check that txtrequireddate.Text is a valid date before trying to convert to a datetime

Cheers,
Hillwaaa
0
 
deNZityAuthor Commented:
Thanks for the reply
the date is valid-- using asp.net compare validator validating datatype date
txtrequireddate.Text = txtrequireddate.Text.ToString("dd-MMM-yyyy ") results in following error

Unable to cast object of type 'System.String' to type 'System.IFormatProvider'.
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.InvalidCastException: Unable to cast object of type 'System.String' to type 'System.IFormatProvider'.

Source Error:


Line 38:
Line 39:         'assign values to vars
Line 40:         txtrequireddate.Text = txtrequireddate.Text.ToString("dd-MMM-yyyy ")
Line 41:         username = txtusername.Text
Line 42:         reqrddate = txtrequireddate.Text
 
0
 
HillwaaaCommented:
Ah - sorry. looking at the error trace, the problem is a sql error - you are trying to insert a non ISO standard date format which is what is giving you the error.  There are two ways to fix

(1) change the format of the string that reqrddate prints in your insert statement to be ISO standard yyyyMMdd
(2) use the following insert:
"values ('" & username & "',convert(datetime,'" & reqrddate & "',XXX),'" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"

where XXX depends on the format of reqrddate in that string.  See http://msdn2.microsoft.com/en-us/library/ms174450.aspx for appropriate values.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
bchoorCommented:
did u try datetime.parse(txtrequireddate.Text)?

http://msdn2.microsoft.com/en-us/library/1k1skd40.aspx

HTH
~BC
0
 
deNZityAuthor Commented:
tried...

"values ('" & username & "',convert(datetime,'" & reqrddate & "',dd-mm-yyyy),'" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"


The name "dd" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
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.Data.SqlClient.SqlException: The name "dd" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
0
 
HillwaaaCommented:
it has to be a number.  if " & reqrddate & " will add a date of the form 22-11-2006 to the string, use:

"values ('" & username & "',convert(datetime,'" & reqrddate & "',105),'" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"

Cheers,
Hillwaaa
0
 
deNZityAuthor Commented:
bchoor,
 tried what you suggested got this error

Conversion failed when converting datetime from character string.
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.Data.SqlClient.SqlException: Conversion failed when converting datetime from character string.



0
 
deNZityAuthor Commented:
Hillwaaa,
"values ('" & username & "',convert(datetime,'" & reqrddate & "',105),'" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"
resulted in this error

Conversion failed when converting datetime from character string.
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.Data.SqlClient.SqlException: Conversion failed when converting datetime from character string.


0
 
HillwaaaCommented:
ok - maybe reqrddate isn't being set properly?

can you set a breakpoint to check what value is being set?

Or do a:
        MessageBox.Show(reqrddate.ToString)
before the "values (" line...

What is the value?
0
 
deNZityAuthor Commented:
this is not a vb.net project this is a asp.net website using vb.net code behind as such messageboxes can't be used.

where would I set  a breakpoint?
0
 
HillwaaaCommented:
set it on the

Line 95:                 Dim myCommand As New SqlCommand(sql, myConnection)

line - then we can see what the "sql" variable is set to.
0
 
deNZityAuthor Commented:
I commented out the queries and ran the page to see what was in
reqrddate = txtrequireddate.Text
label1=reqrddate.text

resulted in 12/12/2006 which was the date entered
0
 
deNZityAuthor Commented:
Heres the sql
            sql      "insert into requests ( [User_Name], [required_date],[NHI], [Event_Number], [ACC_Number], [Request_Date]) values ('','12/12/2006','aaa2222',0,'0','12:00:00 a.m.' )"      String

0
 
HillwaaaCommented:
ok - 12/12/2006 could be dd/MM/yyyy or MM/dd/yyyy

if dd/MM/yyyy try

"values ('" & username & "',convert(datetime,'" & reqrddate & "',103),'" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"

if MM/dd/yyyy try

"values ('" & username & "',convert(datetime,'" & reqrddate & "',101),'" & nhi & "'," & eventnum & ",'" & accnum & "','" & reqstdate & "' )"
0
 
deNZityAuthor Commented:
Both of those resulted in  the original error.. maybe I should post this in the sql serverforum?
0
 
HillwaaaCommented:
OK - from your sql line you have two problems:

(1) the reqrddate is not formatted properly - see my above
(2) the reqstdate is also not formatted properly - 12:00:00 a.m. is not a valid date - you need to do the same conversion on this value to get the MM/dd/yyyy value you have for reqrddate

What you want to end up with is (assuming MM/dd/yyyy):

insert into requests ( [User_Name], [required_date],[NHI], [Event_Number], [ACC_Number], [Request_Date]) values ('',convert(datetime,'12/12/2006',101),'aaa2222',0,'0',convert(datetime,'12/12/2006',101))
0
 
deNZityAuthor Commented:
the request date is set like so...

 Protected Sub TextBox2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtrequestdate.Load
        txtrequestdate.Text = DateTime.Now.ToString("dd-MMM-yyyy")
    End Sub
0
 
deNZityAuthor Commented:
the user puts the date in as dd/mm/yyyy for reqrddate


0
 
HillwaaaCommented:
That sets the text for "txtrequestdate" - how does "txtrequestdate.Text" get into "reqstdate"?  This is the variable you use in your Line 94.

0
 
deNZityAuthor Commented:
its assigned to variable reqstdate=txtrequestdate.text
0
 
deNZityAuthor Commented:
Hillwaaa, Thanks for your effort the points are yours. I have asked the question in the sql server forum
as I think that is where the issue lies.
0
 
HillwaaaCommented:
No worries - I'd say that the problem is two fold - the sql date formatting, and the concatenation of reqstdate into the sql string, as "12:00:00 a.m." will not be valid in sql server.

Cheers,
Hillwaaa.
0
 
deNZityAuthor Commented:
this works

Dim reqrddate As String = Format(CDate(txtrequireddate.Text), "dd MMM yyyy").ToString
Dim reqstdate As String = Format(Date.Now, "dd MMM yyyy").ToString
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 13
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now