Solved

Conversion failed when converting datetime from character string.

Posted on 2006-11-21
23
5,384 Views
Last Modified: 2008-01-09
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
Comment
Question by:deNZity
  • 13
  • 9
23 Comments
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992130
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
 

Author Comment

by:deNZity
ID: 17992229
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
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992264
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
LVL 10

Expert Comment

by:bchoor
ID: 17992285
did u try datetime.parse(txtrequireddate.Text)?

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

HTH
~BC
0
 

Author Comment

by:deNZity
ID: 17992296
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
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992305
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
 

Author Comment

by:deNZity
ID: 17992306
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
 

Author Comment

by:deNZity
ID: 17992316
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
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992384
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
 

Author Comment

by:deNZity
ID: 17992488
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
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992500
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
 

Author Comment

by:deNZity
ID: 17992505
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
 

Author Comment

by:deNZity
ID: 17992531
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
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992534
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
 

Author Comment

by:deNZity
ID: 17992558
Both of those resulted in  the original error.. maybe I should post this in the sql serverforum?
0
 
LVL 16

Expert Comment

by:Hillwaaa
ID: 17992573
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
 

Author Comment

by:deNZity
ID: 17992607
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
 

Author Comment

by:deNZity
ID: 17992617
the user puts the date in as dd/mm/yyyy for reqrddate


0
 
LVL 16

Expert Comment

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

0
 

Author Comment

by:deNZity
ID: 17992741
its assigned to variable reqstdate=txtrequestdate.text
0
 

Author Comment

by:deNZity
ID: 17992792
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
 
LVL 16

Accepted Solution

by:
Hillwaaa earned 500 total points
ID: 17992803
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
 

Author Comment

by:deNZity
ID: 18016414
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
VB.NET 1 28
How to open form using item in Listbox. 8 23
Very Large data in MYSQL 7 73
Get month and date in a format 4 31
I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…

808 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question