The conversion of a char data type to a datetime data type!!

hello all .. I have a form that includes two textboxes (Date and Version) .. When I try to insert the record I get the following error message .. seems that something wrong with my coversion (Data type)

"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
The statement has been terminated."

 

in my SQL database I have the date feild as datetime and the version as nvarchar(max)

this is the code in the vb page .. Can you please tell me how to solve this problem?

Imports System.Data.SqlClient
Imports system.web.configuration

Partial Class Admin_emag_insert
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Record_DateTextBox.Text = DateTime.Now

    End Sub

    Protected Sub clearButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles clearButton.Click
        Me.VersionTextBox.Text = ""
    End Sub

    Protected Sub addButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles addButton.Click
        Dim objConnection As SqlConnection
        Dim objDataCommand As SqlCommand
        Dim ConnectionString As String
        Dim record_date As Date
        Dim version As String
        Dim emagSQL As String

        'save form values in variables
        record_date = Record_DateTextBox.Text
        version = VersionTextBox.Text

        ConnectionString = WebConfigurationManager.ConnectionStrings("HRDBConnectionString").ConnectionString

        'Create and open the connection 
        objConnection = New SqlConnection(ConnectionString)
        objConnection.Open()
        emagSQL = "Insert into E_Magazine (Record_Date, Version ) " & _
        "values('" & record_date & "','" & version & "')"

        'Create and execute the command
        objDataCommand = New SqlCommand(emagSQL, objConnection)
        objDataCommand.ExecuteNonQuery()
        objConnection.Close()

        AddMessage.Text = "A new emagazine was added successfully"

        Me.VersionTextBox.Text = ""

    End Sub
End Class
 
0
Makiya
5/13/2008 4:30:52 PM
asp.net.sql-datasource 29906 articles. 0 followers. Follow

10 Replies
622 Views

Similar Articles

[PageSpeed] 41

 Guess you have to convert record_date to string

 emagSQL = "Insert into E_Magazine (Record_Date, Version ) " & _
"values('" & record_date.ToString() & "','" & version & "')"

Please DO NOT use these kind of queries in your application. Its open to sql injection. Either create stored procedures to do the inserts or use parameterized queries.


Save our world, its all we have! A must watch video Pale Blue Dot

Please use the search feature of the forum before asking a question.
0
XPSCodes
5/13/2008 6:36:37 PM

I added the to string method as you said .. however the same problem is still appearing :(

 

XPSCodes:

Please DO NOT use these kind of queries in your application. Its open to sql injection. Either create stored procedures to do the inserts or use parameterized queries.

 

I didn't get what you mean by the last sintance ?! can you explain more please

0
Makiya
5/13/2008 6:45:32 PM

It needs a lot of explanation, Check this link http://weblogs.asp.net/scottgu/archive/2006/09/30/Tip_2F00_Trick_3A00_-Guard-Against-SQL-Injection-Attacks.aspx

 

 


Save our world, its all we have! A must watch video Pale Blue Dot

Please use the search feature of the forum before asking a question.
0
XPSCodes
5/13/2008 6:59:15 PM

Hi,

In SQL Server as far as I remember as the valid date range begins from 1900-1-1 , I think :)

I guess the valid range message is pointing that.

 

With SQL2008 the date range will enlarge enough to prevent such problems.

 

Eralper

SQL Server Articles

 


http://www.eralper.com
http://www.kodyaz.com
0
eralper
5/13/2008 7:46:59 PM

From BOL :

 Date Range for datetime data type : January 1, 1753, through December 31, 9999

 

Eralper

SQL Server Articles

 


http://www.eralper.com
http://www.kodyaz.com
0
eralper
5/13/2008 7:52:22 PM
Makiya:
When I try to insert the record I get the following error message .. seems that something wrong with my coversion (Data type)
        Dim record_date As Date

        emagSQL = "Insert into E_Magazine (Record_Date, Version ) " & _
        "values('" & record_date & "','" & version & "')" 
There is no such thing as Date type in T-SQL. That is, you need to supply full DateTime in proper culture to SQL server.
Try to 
- declare your record_date as DateTime, not just Date;
- validate on-client the entered Date string;
- use Parse, TryParse or ParseExact methods of DateTime to handle the entered Date string;
- yes, use parameterized queries;
But, better, consider using Drop Down Lists to select date parts, and then assemble the DateTime value in code-behind.
0
SergeyS
5/13/2008 9:56:09 PM

Hello,

It is best to work with datetime string values in format YYYYMMDD which is Chinese datetime format.

Because DDMMYYYY and MMDDYYYY format conversions may cause errors sometimes.

 


http://www.eralper.com
http://www.kodyaz.com
0
eralper
5/14/2008 5:52:48 AM

Any other solution .. coz I am not really aware of imlementing the above solutions ...

Moreover, I need to view the date in the following foramt dd/mm/yyyy

 I tried convert.todatetime() but the error is still apearing ...

 

 

Please HELP

0
Makiya
5/18/2008 6:23:43 AM

There is a function like: bool datetime.tryparse(char val, datetime result out). You can pass the char string to that, and check the bool result to see if it worked right.

0
valenumr
5/18/2008 7:09:11 AM

Use try catch in button click handler. Print the value of record_date string to the debug window (immediate window) and see what you are trying to pass and if it is meaningful and within the valid range or a formatting issue. Post those values here if you need further help after your try. Try to check if the record_date accepts null in the database Hope this helps

Regards, Vasu


Regards, Sreenivas (Vasu) Chaparala
ps:Unless a question, this is an attempt to provide guidance. Turning this into a solution, if required, is ones own responsibility. Expecting the entire solution as-is is inappropriate for any professional.
0
vasuvani
5/18/2008 4:47:56 PM
Reply:

Similar Artilces:

System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
After testing out the application i write on the local pc. I deploy it to the webserver to test it out. I get this error. System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. Notes: all pages that have this error either has a repeater or datagrid which load data when page loading. At first I thought the problem is with the date, but then I can see that some other pages that has datagrid ( that has a date field) work just fine. anyone having this problem before?? hopefully you guys can help...

System.Data.SqlClient.SqlException: The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
After clicking my update button I'm receiving this error:    The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated. 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 conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Hey, I have a big problem that i wanna search data from SQL by DateTime like thatselect * from test where recorddate='MyVariableWhichHoldDate'i use variable that holds Date info.i searched a lot infomation on net but there is no perfect solution. i know why this occur but there is no function to solve this problem. i used a lot of ways. it accept yyyy-mm-dd format but my variable format is dd-mm-yyyyy . is there any function for this problem? and any other solution.thanks for ur attentionregards Just do select * from table where dateField = '1-1-2005'. This will work..Nick The safest for...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
 Hello,When i run my project in VS IDE i dont get this below mentioned error but assoon as i put it in IIS of my server machine i get this error.I am using this application since months and wasn't getting any error. But recently when my admin made some changes in server..This error started coming. I have no help from my admin regarding this.  Let me know if i have to do some changes in c# code or in database or in windows server machine or in IIS or in crystal report properties !! The error is as follows : Normal 0 false false false ...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Normal 0 false false false MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin:0in; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-b...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
I still don't know what is happening with my application. I used before in another page the formview control and I didn't have the out of range Date error. It was normally. But now, I'm doing everything manually and I don't know why, but I'm with this problem. I need to safe this problem today... Here go my code!Thanks Raphael <%@ Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SQLClient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> ...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
 Please help me its give me the error on server but run successfully on my local  The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. 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 conversion of a char data type to a datetime data type resulted in an out-of-range datetime...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
  Hi , i m inserting the values in the fallowing ways INSERT INTO LoginHistory([UserID],[LoginTime],[LoginIP])VALUES('NilCom1Ad01','13-04-2009 4:52:54 PM','127.0.0.1' ) Still i  m Geting errror  The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.The statement has been terminated.Plz  help me  I'm wondering if your database is expecting month/day/year, in which case 13 would be causing your problem.  Change the date to 04-13-2009 and give it a try.C# <---> V...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
Hello this is my code: ( I want to see if the date is in a month of a selected year)Dim command As New SqlCommand command.Connection = connection command.CommandType = CommandType.Text command.CommandText = "SELECT count(*) fROM tblRequests r WHERE r.StateID =4 AND r.CategoryID <>2 AND r.CompletionDate BETWEEN '" & year & "-" & teller & "-01' AND '" & year& "-" & teller + 1 & "-01'"Dim objaantal As Object = command.ExecuteScalar() Dim Incidents As Integer If Not objaantal Is No...

conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
  When I run this error I get this error  ' The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.' select distinct pro.prodname, pro.price, pro.description, pro.fromdate, pro.todate, pro.pic1 from products pro inner join booking on pro.category=booking.category where pro.category=1 and '12/11/2008' between pro.fromdate and pro.todate and '18/12/2008' between pro.fromdate and pro.todate and '12/11/2008' not between booking.checkin and booking.checkout and '18/12/2008' not between booking.chec...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. #2
Advance thanks ....... My table is  TimeSheet:-----------------------------------  CREATE TABLE [dbo].[TimeSheet](    [autoid] [int] IDENTITY(1,1) NOT NULL,    [UserId] [int] NOT NULL,    [starttime] [datetime] NOT NULL,    [endtime] [datetime] NOT NULL,    [summary] [nvarchar](50) NOT NULL,    [description] [nvarchar](50) NULL,    [dtOfEntry] [datetime] NOT NULL,    [Cancelled] [bit] NULL) ON [PRIMARY] My Query is------------------ insert into tim...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. #2
sombedoy can solve this problem:   my code:   '######################################## '# Create values for XML File # '########################################Dim command As New SqlCommand command.Connection = connection command.CommandType = CommandType.Text  Dim datum1, datum2 As DateTime   datum1 = teller6.ToString & "/01/" & jaar & " 0:00:00" datum2 = (teller6 + 1).ToString & "/01/" & jaar & " 0:00:00"   command.CommandText = "SELECT count(*) fROM tblRequests r WHER...

Error : The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
 My website is facing one problem after hosting to the server.When i execute my code from local(india) all working fine.But when i host it to UK,the error coming "The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value" . I used Culture=en-GB in web.config.But not solved.This error is coming to all pages where datetime value is using..Please help me ..  Can you post your code or screenshot showing the error on some code line...  Thanks,santosh_maharajaPlease mark as answer if you got expected solution.  this is ...

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. #2
I still don't know what is happening with my application. I used before in another page the formview control and I didn't have the out of range Date error. It was normally. But now, I'm doing everything manually and I don't know why, but I'm with this problem. I need to safe this problem today... Here go my code!Thanks Raphael <%@ Page Language="VB" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SQLClient" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <script runat="server"> ...

Web resources about - The conversion of a char data type to a datetime data type!! - asp.net.sql-datasource

Conversion (law) - Wikipedia, the free encyclopedia
Its criminal counterpart is theft . Examples are seen in cases where trees are cut down and the lumber hauled from the land by someone not having ...

Sonny Bill Williams' transformation due to conversion to Islam, Anthony Mundine says
He went from being savaged for walking out on the Bulldogs to becoming one of the world's most respected rugby union stars. Anthony Mundine believes ...

Family of Enrique Marquez unaware of his 2014 marriage, conversion to Islam
The family members of Enrique Marquez, the man linked to the San Bernardino massacre, said they were unaware he was married or that he had converted ...

Revisiting Carlos Martinez's rotation conversion
... thanks to his pitch mix, then it sure sounded like it could be possible. Now, almost a full year later, I wanted to revisit Martinez's conversion. ...

Dow to Force Conversion of Buffett Preferreds If Rally Holds
Bloomberg Dow to Force Conversion of Buffett Preferreds If Rally Holds Bloomberg Dow Chemical Co., which has been paying $255 million annually ...

Tory MP: 'It is time to make gay conversion therapy illegal'
Gay-conversion therapies were debated in the house of parliament this afternoon with one Conservative MP calling for legislation to make them ...

Roth IRA conversion is complicated
Tax rules governing IRAs are complex and ever changing, so if you're considering a Roth conversion, do some legwork first.

Russian Minister Confirms Plans to Ban Bitcoin-to-Fiat Conversions
Russia's Deputy Finance Minister has confirmed the country's plans to penalise the conversion of cryptocurrencies such as bitcoin into the ruble. ...

Del Rio explains why Raiders went for late two-point conversion
... A's Sharks Warriors Kings 49ers Raiders Quakes Insiders More Tickets Shop Watch Del Rio explains why Raiders went for late two-point conversion ...

Get a free copy of powerful DVD ripping and video conversion software
DVD players are going the way of the Walkman, leaving many of us with vast libraries of obsolete discs. Of course the movies and TV shows themselves ...

Resources last updated: 12/15/2015 9:58:49 PM