String to Date conversion - asp.net

Hi I am receiving an error of string to date conversion
here's my script
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
dim oVal as New Collections
'Time stamp
oVal.Add(DateTime.ParseExact(Request.Cookies("TimeStarted").Value.ToString, "dd-MM-yyyy HH:mm:ss", Nothing), "ofield_starttime")
oVal.Add(dt.ToString("dd-MM-yyyy HH:mm:ss"), "ofield_stoptime")
Savetime(oVal)
and under public function saveTime(oVal as Collection)
Dim sQuery As New SqlCommand
sQuery.CommandType = CommandType.StoredProcedure
sQuery.CommandText = "PSC_Timestamp"
With sQuery.Parameters
.AddWithValue("#PSCStart", Convert.ToDateTime(oVal("ofield_starttime")))
.AddWithValue("#PSCStop", CDate(oVal("ofield_stoptime")))
End With
sQuery.Connection = myConnection
If myConnection.State = 1 Then 'check if connection open
myConnection.Close()
End If
myConnection.Open()
sQuery.ExecuteNonQuery()
myConnection.Close()
I am receiving this error
Conversion from string "13-07-2015 13:09:38" to type 'Date' is not valid.
A helping hand is highly appreciated...thanks in advance.

The problem is you don't specify where your error is happening. If it's the following line:
DateTime.ParseExact(Request.Cookies("TimeStarted").Value.ToString, "dd-MM-yyyy HH:mm:ss", Nothing)
... then what I find interesting is that you are passing Nothing to the final IFormatProvider provider parameter. When you do that, it defaults to the current culture. Is it possible that your current culture is messing up how the data is being parsed?
To ensure consistent behavior, try passing CultureInfo.InvariantCulture instead:
DateTime.ParseExact(Request.Cookies("TimeStarted").Value.ToString, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture)
If your error is happening with the following lines:
.AddWithValue("#PSCStart", Convert.ToDateTime(oVal("ofield_starttime")))
.AddWithValue("#PSCStop", CDate(oVal("ofield_stoptime")))
Then, make sure to change the date conversion logic to use DateTime.ParseExact and you should be fine.

I found out - to rectify this scenario I have to set the calendar format to a desired settings that has the same format that I am using with my application. This resolved the issue of error in date conversion.

Related

cType : string to date throwing InvalidCastException (ASP) (VB.NET)

I am getting exception on following lines
InspectionDate = "07/15/2014"
If CType(InspectionDate, Date) > Date.Today Then
'Here comes my logic etc
'Here comes my logic etc
'Here comes my logic etc
End If
When i debugged i see Date.Today = #7/15/2014#
Can any one please help on this.
Thanks..
Try like this
Dim dt As Date = Date.ParseExact("07/15/2014","MM/dd/yyyy", CultureInfo.InvariantCulture);
IF dt > Date.Today Then
'CODE HERE
END IF
Check the full documentation at msdn
InspectionDate = "07/15/2014"
If DateTime.Parse(InspectionDate) > Date.Today Then
'Here comes my logic etc
'Here comes my logic etc
'Here comes my logic etc
End If
try like this
Before compare both dates use the TryParse method
Dim dateValue as Date
InspectionDate = "07/15/2014"
If (Date.TryParse(InspectionDate, dateValue) > Date.Today Then
'your code here
End If
check the metod in the MSDN
check the description

cannot convert string to date

Hello stack overflow residents! this is my first post and i'm hoping to receive some help.
I've searched but because I'm still very new, i was not able to full find/understand my answer.
I keep encountering this error:
Message: Conversion from string "" to type 'Date' is not valid. File:
~/reports/pendingshipments.aspx Function: btnExportXls_Click Stack
Trace: at
Microsoft.VisualBasic.CompilerServices.Conversions.ToDate(String
Value) at reports_default.btnExportXls_Click(Object sender, EventArgs
e) in C:\Users\jet.jones\Documents\ERIRoot\ERITitan\ERITitan.ssa\Web
Application\reports\pendingshipments.aspx.vb:line 75
Here is my code:
on App_code
**Public Function Reports_PendingShipments(ByVal intClientID As Integer, ByVal strMinDate As Date?, ByVal strMaxDate As Date?, ByVal xmlSiteID As String) As DataTable
'=================================================================================
' Author: Jet Jones
' Create date: 2013.05.28
' Description: Returns a data table with pending shipments for the sites specified
'=================================================================================
Dim objConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("Titan").ToString)
Dim cmdGet As New SqlCommand("spReports_PendingShipments", objConn)
Dim parClientID As New SqlParameter("#ClientID", SqlDbType.Int)
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
Dim parSiteID As New SqlParameter("#Sites", SqlDbType.Xml)
Dim objAdapter As New SqlDataAdapter(cmdGet)
Dim objTable As New DataTable
parClientID.Value = intClientID
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
parSiteID.Value = xmlSiteID
'set up the command object
cmdGet.Connection = objConn
cmdGet.CommandType = CommandType.StoredProcedure
'add the parameters
cmdGet.Parameters.Add(parClientID)
cmdGet.Parameters.Add(parMinDate)
cmdGet.Parameters.Add(parMaxDate)
cmdGet.Parameters.Add(parSiteID)
'open the connection
objConn.Open()
'execute the query and fill the data table
objAdapter.Fill(objTable)
'return the data table
Reports_PendingShipments = objTable
'clean up
objConn.Close()
objConn = Nothing
End Function**
my aspx.vb page calls this function this way (Get the values from the query):
objTable = Reports_PendingShipments(ucClientSearch.Value,
txtMinDate.Text, txtMaxDate.Text, strSites)
I'm passing the variable strSites because the website permissions allow for users to have access to one or more site locations, and if a report is run and the user selects "All Sites" from the dropdown, I only want to send the sites they have permissions to via XML.
If I'm missing any information please let me know!
anyone's prompt response is so greatly appreciated.
The problem is that your code is expecting empty dates to be NULL, it doesn't check for empty strings. You need something like this:
if len(strMinDate)=0 then
strMinDate = "01/01/1980"
end
Not sure what you want to default the minimum date to, but you need to add code similar to the IF statement above
Be sure to add this code prior to using the variable a few lines later...
First of all, you adding MaxDate parameter twice:
Dim parMinDate As New SqlParameter("#MaxDate", IIf(Not strMinDate.HasValue, DBNull.Value, strMinDate))
Dim parMaxDate As New SqlParameter("#MaxDate", IIf(Not strMaxDate.HasValue, DBNull.Value, strMaxDate))
And moreover, then you setting parameters values wuthout check for HasValue:
parMinDate.Value = strMinDate
parMaxDate.Value = strMaxDate
Remove these lines and fix min date parameter name

Inserting null values into date fields?

I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function

SqlClient.SqlCommand Bombing Out

Still new to .NET, but this looks OK to me. I can't figure out what's going on. I'm trying to add 1 parameter to a SqlCommand. It is an integer in SQL Server, and I'm passing an integer to it.
It hangs on the Command.Parameters.Add(PolicyNo) code line and kicks out an "unable to process due to internal error".
I've also tried
Command.Parameters.AddWithValue("#PolicyNumber", PolicyNo)
But to no avail. It bombs out with the same error message. Here's the code:
Public Function GetPolicyObj(ByVal PolicyNo As Integer) As PolicyInfo Implements ILetterWriter.GetPolicyObj
Dim SQLcon As New SqlClient.SqlConnection
'Establish the connection
SQLcon.ConnectionString = "Data Source=Hosed;Initial Catalog=MyCat;User ID=Goofy;Password=OpenSesame;"
SQLcon.Open()
Using Command As New SqlClient.SqlCommand("sp_GetPolicyInfo", SQLcon)
Command.CommandType = CommandType.StoredProcedure
Command.Parameters.Add(PolicyNo) 'Bombs on this line
Command.Connection.Open()
Dim reader As SqlClient.SqlDataReader = Command.ExecuteReader
Any Ideas?
Thanks,
Jason
Have you tried creating the parameter like this:
Dim param as new SqlParameter()
param.ParameterName = "ParamName"
param.Value = PolicyNo
Command.Parameters.Add(param)
Not entirely sure if this is the problem should be, but you are not giving the parameter object a name, only passing the value which will thrown an exception, you have to give the parameter a name as well
Command.Parameters.Add(new SqlParameter("PolicyNo",PolicyNo))
Command.Parameters.Add() takes a SqlParameter object as its parameter. So you can't just send the integer.
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson06.aspx
Try:
Command.Parameters.AddWithValue("#PolicyNo", PolicyNo);
Maybe you could try explicitly typing your parameter:
Command.Parameters.Add("#PolicyNumber", SqlDbType.Int)
Command.Parameters("#PolicyNumber").Value = PolicyNo
And make sure your parameter name and datatype match what's in the stored procedure.

Returning date from Stored procedure in ASP.Net/VB.Net

I want to execute a method on VB.Net to return a date which is in the stored procedure. I tried using ExecuteScalar but it doesnt work it retruns error
'Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query'
Any help would be much appreciated please?
thank you
below is the code
Public Function GetHolidaydate(ByVal struserID as String) As DateTime
Dim objArgs1 As New clsSQLStoredProcedureParams
objArgs1.Add("#userID", Me.Tag)
objArgs1.Add("#Date", 0, 0, ParameterDirection.Output)
Return (CDate(ExecuteScalar(clsLibrary.MyStoredProcedure.GetHolidayDate, objArgs1)))
End Function
I think that your problem is here:
objArgs1.Add("#Date", 0, 0, ParameterDirection.Output)
You are adding 0's where they should be typeOf DateTime.
EDIT
Public Function GetHolidayDate(ByVal struserID as String) AS DateTime
Dim con As New SqlConnection(yourSQLConnectionString)
Dim cmd As New SqlCommand
Dim date As DateTime
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "yourStoredProcedureName"
cmd.Parameters.Add("#userID", Me.Tag)
cmd.Parameters("#Date").Direction = ParameterDirection.Output
cmd.ExecuteScalar()
date = cmd.Parameters("#Date").Value
con.Close()
Return date
End Function
Looks like the error you are getting is a SQL error not a VB.Net error. Are you trying to convert a datetime to an int somewhere?
You could you try running the ExecuteNonQuery() method to see if you get the same error.
You could also run SQLProfiler and see exactly what SQL is being run.
You could then try running this SQL is SQL Server Management Studio
You add two parameters - but you said it should return the later one ?
So it must be
date DateTime = cmd.ExecuteScalar()
REM date = cmd.Parameters("#Date").Value
con.Close()

Resources