Invalid cast from 'Boolean' to 'DateTime' - vb.net

I keep getting this error
Invalid cast from 'Boolean' to 'DateTime'
when the codes below try to execute.
I am basically trying to update my auction_item table where the "closedate < todayDate" is met.
This is where the error fires [Dim forupdate As Date = Convert.ToDateTime(closedate < todayDate)]
con.Open()
CMD = New SqlCommand("SELECT auction_item_close_date FROM auction_items WHERE (auction_item_status_id = 1)", con)
DR = CMD.ExecuteReader()
DR.Read()
Dim closedate As Date
closedate = Convert.ToDateTime(DR(0))
con.Close()
Dim todayDate As Date = DateAndTime.Today
Dim forupdate As Date = Convert.ToDateTime(closedate < todayDate)
con.Open()
If closedate < todayDate Then
SQL = "UPDATE auction_items SET auction_item_status_id = 2, auction_item_open_closed = 'closed' WHERE auction_item_close_date = '" & forupdate & "'"
CMD = New SqlCommand(SQL, con)
CMD.ExecuteNonQuery()
con.Close()
End If

The error is on this line:
Dim forupdate As Date = Convert.ToDateTime(closedate < todayDate)
closedate < todayDate returns true or false depending on whether closedate is before todayDate.
That value can not be converted to a DateTime and this is what the exception says. Maybe you need to rethink what the line is supposed to do.

Related

Why SQL Server datetime datatype and datetimepicker search no result on VB.NET?

I am doing a function to search for records between 2 date on VB.NET. But I'm not sure is the conversion error or what the result is not showing. I store the date and time in database with DATETIME datatype, and I compare it with the datetimepicker of VB.NET. I guess it is because the datetime store in database include the date and the datatimepicker do not have time in it so the comparison to search the records will never be appear since the comparison is wrong because the datetimepicker do not have time in it.
Here's the code. The dateSelectFrom.value and dateSelectTo.value is the value of the datetimepicker
If rbFirstDate.Checked Then
Dim ds1 As String = Format(dateSelectFrom.Value, "YYYY-MM-DD")
cmd.CommandText = "SELECT OrderList.Id, OrderList.timeOrder,OrderDetail.foodID, Food.foodName,OrderDetail.qty, Food.price, OrderDetail.subtotal FROM OrderDetail INNER JOIN Food on OrderDetail.foodID = Food.Id INNER JOIN OrderList on OrderDetail.orderID = OrderList.Id WHERE (timeOrder = CONVERT(DATETIME, '" & ds1 & "', 102)) order by timeOrder"
End If
If rbBetweenDate.Checked Then
Dim ds1 As String = Format(dateSelectFrom.Value, "YYYY-MM-DD")
Dim ds2 As String = Format(dateSelectTo.Value, "YYYY-MM-DD")
cmd.CommandText = "SELECT OrderList.Id, OrderList.timeOrder,OrderDetail.foodID, Food.foodName,OrderDetail.qty, Food.price, OrderDetail.subtotal FROM OrderDetail INNER JOIN Food on OrderDetail.foodID = Food.Id INNER JOIN OrderList on OrderDetail.orderID = OrderList.Id WHERE (timeOrder BETWEEN CONVERT(DATETIME, '" & ds1 & "', 102) AND CONVERT(DATETIME, '" & ds2 & "', 102)) order by timeOrder"
End If
I had try to put the time format behind the date but it shows error conversion of datetime from string. Which the code looks like this :
Dim ds1 As String = Format(dateSelectFrom.Value, "YYYY-MM-DD HH:MI:SS")
Am I doing the conversion the wrong way or how do I assign the time to the datetimepicker.value?
I'm kinda confused by this datetimepicker and DATETIME datatype.
You should parameterize your query. Not only would this fix potential SQL injection vulnerabilities, but it will likely fix your underlying issue too.
Take a look at this example:
Dim commandString As String = "
SELECT
OrderList.Id,
OrderList.timeOrder,
OrderDetail.foodID,
Food.foodName,
OrderDetail.qty,
Food.price,
OrderDetail.subtotal
FROM
OrderDetail
INNER JOIN Food ON
OrderDetail.foodID = Food.Id
INNER JOIN OrderList ON
OrderDetail.orderID = OrderList.Id
WHERE
{{where}}
ORDER BY
OrderList.timeOrder;"
If (rbFirstDate.Checked) Then
commandString = commandString.replace("{{where}}", "OrderList.timeOrder = CONVERT(DATETIME, #0, 102)")
ElseIf rbBetweenDate.Checked Then
commandString = commandString.replace("{{where}}", "OrderList.timeOrder BETWEEN CONVERT(DATETIME, #0, 102) AND CONVERT(DATETIME, #1, 102)")
End If
Dim con As OleDbConnection
Try
con = New OleDbConnection("My Connection String Here")
Using cmd As OleDbCommand = New OleDbCommand(commandString, con)
' parameterize the query here
cmd.Parameters.Add("#0", OleDbType.Date).Value = dateSelectFrom.Value
If rbBetweenDate.Checked Then
cmd.Parameters.Add("#1", OleDbType.Date).Value = dateSelectTo.Value
End If
con.Open()
' do something with cmd here
con.Close()
End Using
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
' Close the connection if it was left open(exception thrown)
con.Close()
End If
con.Dispose()
End If
End Try
Obviously if you're using SQL Server then swap out the OLEDB namespace, but this is the basic gist.
The .Value property of a DateTimePicker returns a DataTime. Don't change it to a string and then have the database change it back to a date. The use of parameters should line up your .net DateTime with the Sql Server DateTime.
Private Function GetOrders() As DataTable
Dim dt As New DataTable
Dim sb As New StringBuilder
sb.Append("SELECT
OrderList.Id,
OrderList.timeOrder,
OrderDetail.foodID,
Food.foodName,
OrderDetail.qty,
Food.price,
OrderDetail.subtotal
FROM OrderDetail
INNER JOIN Food on OrderDetail.foodID = Food.Id
INNER JOIN OrderList on OrderDetail.orderID = OrderList.Id
WHERE 1 = 1")
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
'this parameter will be used if either radio button is checked
cmd.Parameters.Add("#FirstDate", SqlDbType.DateTime).Value = dateSelectFrom.Value
If rbFirstDate.Checked Then
sb.AppendLine(" And timeOrder = #FirstDate")
ElseIf rbBetweenDate.Checked Then
sb.AppendLine(" And timeOrder BETWEEN #FirstDate AND #SecondDate")
cmd.Parameters.Add("#SecondDate", SqlDbType.DateTime).Value = dateSelectTo.Value
End If
sb.AppendLine(" Order By timeOrder;")
Debug.Print(sb.ToString) 'Just to check if everthing was added properly
cmd.CommandText = sb.ToString
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function

Updating SQL Server DateTime columns in VB.NET

When updating records some DateTime values may look like 2015-06-25T01:35:52Z or 13 jun 2014
So when writing query I do:
Dim Query As String = "Update Activities set ActivityDate = '" & theDate & "' where customerid = 10"
(using vb.net)
but results in error. Is there a DateTime conversion I can use?
Using Data.SqlClient.SqlCommand.Parameters.Add:
MSDN: SqlCommand.Parameters Property
A parameterized query can handle this datetime conversion for you:
Protected Sub UpdateCustomerActivityDate(customerID As Integer, activityDate As DateTime)
Dim sql As String = "Update Activities set ActivityDate = #activityDate where customerid = #customerID"
Dim cmd As New Data.SqlClient.SqlCommand(sql)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("#customerID ", Data.SqlDbType.Int).Value = customerID
cmd.Parameters.Add("#activityDate ", Data.SqlDbType.DateTime).Value = activityDate
Try
Using connection As New SqlConnection(YourConnectionString)
connection.Open()
cmd.Connection = connection
cmd.ExecuteNonQuery()
End Using
Catch ex As Exception
Throw ex
End Try
End Sub

Error with searching between two dates on mschart

I have a problem with MSchart control. I have 2 fields on my database for date and time.
When I connect to my database and load X and Y values to my chart, there is no problem, but when i use search between 2 date in my query then mschart loads nothing. I'm using Text format for inDate1 and inTime1, here is my code:
Dim con As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excel
Dim query As String = "SELECT inDate1,inTime1 FROM loginlog where personID=" + TextBox1.Text+" and inDate1 between "+ TextBox2.Text " and " + TextBox3.Text
Dim mycon As New OleDbConnection(con)
Dim command As New OleDbCommand(query, mycon)
mycon.Open()
chart1.DataSource = command.ExecuteReader()
chart1.Series(0).XValueMember = "inDate1"
chart1.Series(0).YValueType = ChartValueType.Time
chart1.Series(0).YValueMembers = "inTime1"
chart1.DataBind()
mycon.Close()
You really do not want to use text for dates. Instead, convert them to DateTimes (e.g. with DateTime.TryParse) and pass them as SQL parameters.The remark about passing as an SQL parameter applies to all parameters, including the personID.
So, your code could look something like:
Dim startDate As DateTime
Dim endDate As DateTime
If Not DateTime.TryParse(TextBox2.Text, startDate) Then
' there was an error parsing - do something useful
startDate = New DateTime(2000, 1, 1)
End If
If Not DateTime.TryParse(TextBox3.Text, endDate) Then
' there was an error parsing - do something useful
endDate = New DateTime(2100, 12, 31)
Else
' add a day to include it in the range selected in the SQL query
endDate = endDate.AddDays(1)
End If
Dim query As String = "SELECT inDate1, inTime1 FROM loginlog WHERE personID = #PersonID AND inDate1 BETWEEN #StartDate AND #EndDate"
Dim mycon As New OleDbConnection(con)
Dim command As New OleDbCommand(query, mycon)
command.Parameters.Add(New OleDbParameter With {.ParameterName = "#PersonID", .OleDbType = OleDbType.VarWChar, .Value = TextBox1.Text})
command.Parameters.Add(New OleDbParameter With {.ParameterName = "#StartDate", .OleDbType = OleDbType.Date, .Value = startDate})
command.Parameters.Add(New OleDbParameter With {.ParameterName = "#EndDate", .OleDbType = OleDbType.Date, .Value = endDate})
' now execute the query...

Conversion of string to date type while passing from vb.net to sql server

I had the same issue while passing date variable from vb.net to SQL Server. I tried with Parameters as suggested above. Still I am facing the same issue. Pl guide.
Dim today As String
today = System.DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss")
Dim todate As DateTime = DateTime.ParseExact(today, "MM-dd-yyyy hh:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
SQLCom.CommandType = CommandType.Text
SQLCom.Parameters.AddWithValue("#TODAY", CType(todate, Date))
SQLCom.CommandText = "SELECT DATEDIFF(MM,FORMAT(UPD_DATE,'dd-MM-yyyy'),FORMAT(#TODAY,'dd-MM-yyyy')) AS DATE_DIFF FROM tblEMP WHERE EMPID = '" & ID & "';"
Try
Dim daEmpExp As New SqlDataAdapter
daEmpExp.SelectCommand = SQLCom
SQLConn.Open()
daEmpExp.Fill(dsEmpExp)
SQLConn.Close()
Catch ex As Exception
MsgBox("Sorry!!! " & ex.Message)
Finally
If SQLConn.State = ConnectionState.Open Then
SQLConn.Close()
End If
End Try
End If
Return dsEmpExp
Still it catches error "Conversion failed when converting date and/or time from character string."
Why you need to convert date to string back and forth? Try to simply pass DateTime.Now as sql command parameter :
SQLCom.CommandType = CommandType.Text
SQLCom.Parameters.AddWithValue("#TODAY", System.DateTime.Now)
SQLCom.Parameters.AddWithValue("#ID", ID)
SQLCom.CommandText = "SELECT DATEDIFF(MM,FORMAT(UPD_DATE,'dd-MM-yyyy'),FORMAT(#TODAY,'dd-MM-yyyy')) AS DATE_DIFF FROM tblEMP WHERE EMPID = #ID;"
Try
......
End Try

Query a database and insert if not present

I would like to add a way to see if an entry is already in a connected database in the following code. If it is then don't add the entry and pop up a dialog saying something to the effect of "already been scanned" and if it is not, proceed as usual.
Using connection As New SqlClient.SqlConnection("Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True;Pooling=False;Encrypt=False"), _
cmd As New SqlClient.SqlCommand("INSERT INTO [XXXXX] (TrackingNumber, Date) SELECT #TrackingNumber, #Date WHERE NOT EXISTS (SELECT * FROM([XXXXX])WHERE TrackingNumber = #TrackingNumber AND Date = #Date)", connection)
cmd.Parameters.Add("#TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum
cmd.Parameters.Add("#Date", SqlDbType.DateTime, 8).Value = TrDate
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
End Using
You should be able to put your inputs into a subquery that checks for redundancy:
INSERT INTO [XXXXXXX] (TrackingNumber, Date)
SELECT #TrackingNumber, #Date from DUAL
WHERE NOT EXISTS (
SELECT *
FROM [XXXXXXX]
WHERE TrackingNumber = #TrackingNumber AND Date = #Date)
My VB.NET might be somewhat off but hopefully this should give the general idea!
Dim rowsAffected AS Integer
Using connection As New SqlClient.SqlConnection("Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True;Pooling=False;Encrypt=False"), _
cmd As New SqlClient.SqlCommand("INSERT INTO [XXXXX] (TrackingNumber, Date) SELECT #TrackingNumber, #Date WHERE NOT EXISTS (SELECT * FROM [XXXXX] WHERE TrackingNumber = #TrackingNumber)", connection)
cmd.Parameters.Add("#TrackingNumber", SqlDbType.VarChar, 50).Value = TrNum
cmd.Parameters.Add("#Date", SqlDbType.DateTime, 8).Value = TrDate
connection.Open()
rowsAffected = cmd.ExecuteNonQuery()
connection.Close()
End Using
If rowsAffected = 0 Then
MsgBox "Scanned Already"
Else
MsgBox "Inserted Succesfully"
End If