SQL in VB.net showing wrong dates - vb.net

In VS2017 I am pulling dates from an Access accdb file to show in a ReportViewer. However, all of my date queries pull all of the fields in each date regardless of what I put in the variables.
Here is the input formatting and var run
SignupDateStart.Format = DateTimePickerFormat.Custom
SignupDateStart.CustomFormat = "MM / dd / yyyy"
Dim strSignupDateStart As String = SignupDateStart.ToString
strSignupDateStart = lblStartDate.Text
SignupDateEnd.Format = DateTimePickerFormat.Custom
SignupDateEnd.CustomFormat = "MM/dd/yyyy"
Dim strSignupDateEnd As String = SignupDateEnd.ToString
strSignupDateEnd = lblEndDate.Text
frmSignupReportQuery2.getFilterValues(strSignupDateStart, strSignupDateEnd)
Here is the getFilterValues sub:
Public Shared Sub getFilterValues(ByVal date1 As String, ByVal date2 As String)
Try
frmSignupReportQuery2.MemberBaseTableAdapter.
FillBy(frmSignupReportQuery2.DataSet2.MemberBase, date1, date2)
Catch ex As Exception
End Try
End Sub
and here is the query i use for dataset2
SELECT ID, ccnumberexp, EntireName, address, stateinit, zip, age, email, ccnumber, SignupDate, MemberTypes
FROM MemberBase
WHERE SignupDate BETWEEN #?# AND #?#
This is a school project and so any vulnerabilities are not a issue. Any help is appreciated.
EDIT 1
Here is the vb.net code
Public strMembershipType As String = ""
Public strMembershipTypeNum As String = ""
SignupDateStart.CustomFormat = "MM/dd/yyyy"
SignupDateStart.Format = DateTimePickerFormat.Custom
strSignupDateStart = Convert.ToDateTime(SignupDateStart.Value)
MessageBox.Show(strSignupDateStart)
SignupDateEnd.CustomFormat = "MM/dd/yyyy"
SignupDateEnd.Format = DateTimePickerFormat.Custom
strSignupDateEnd = Convert.ToDateTime(SignupDateEnd.Value)
MessageBox.Show(strSignupDateEnd)
frmSignupReportQuery2.getFilterValues(strSignupDateStart, strSignupDateEnd)
frmSignupReportQuery2.Show()
I am now getting an "InvalidCastException: Conversion from string "" to type 'Date' is not valid." Error on the
strSignupDateStart = Convert.ToDateTime(SignupDateStart.Value) line
Here is the revised query
SELECT ID, ccnumberexp, EntireName, address, stateinit, zip, age, email,
ccnumber, SignupDate, MemberTypes
FROM MemberBase
WHERE SignupDate BETWEEN ? AND ?
EDIT 2
The class I am taking is not for programming, it is analysis of system design and projects. The teacher I have does not know how to do what I am doing. Most others in my class are using some mix of MSaccess. I wish I had someone to show me how to do parameterized queries in datasets, But I will get to it. This is my current implementation.
Try
SignupQuery.ReportViewer1.Clear()
SignupQuery.getFilterValues(SignupDateStart.Value, SignupDateEnd.Value)
SignupQuery.ReportViewer1.RefreshReport()
SignupQuery.Show()
Catch ex As Exception
End Try
Public Shared Sub getFilterValues(ByVal date1 As Date, ByVal date2 As Date)
Try
here is the subprocedure:
SignupQuery.MemberBaseTableAdapter.FillBy(SignupQuery.DataSet2.MemberBase,
date1, date2)
Catch ex As Exception
End Try
end sub
I appreciate everyone's input.

First, do use parameters. School or not, you will have to learn that anyway, sooner or later.
But, if you insist on concatenating, your code can be reduced to:
strSignupDateStart = SignupDateStart.Value.ToString("#yyyy'/'MM'/'dd#")
MessageBox.Show(strSignupDateStart)
strSignupDateEnd = SignupDateEnd.Value.ToString("#yyyy'/'MM'/'dd#")
MessageBox.Show(strSignupDateEnd)
frmSignupReportQuery2.getFilterValues(strSignupDateStart, strSignupDateEnd)
frmSignupReportQuery2.Show()
This will pick the true DateTime values of the DateTimePickers and convert these to string expressions using a format understood by Access SQL: #yyyy/mm/dd#

Don't convert the dates to strings. If you ever find yourself converting a date to a string for use with an SQL database, you're doing something very wrong.
This is partly for security issues, but it's also just make things easier. Rely on the features of the dataset and ADO.Net to handle the formatting for your SQL dates. Give them a .Net DateTime value, and they already know how to convert it to make sure it's exactly what your database needs. This will also nicely side-step the problem you have here. But as this is for school, I'd like to see you make your own attempt before I show you any code.
I also wonder about this:
Dim strSignupDateStart As String = SignupDateStart.ToString
strSignupDateStart = lblStartDate.Text
and this:
Dim strSignupDateEnd As String = SignupDateEnd.ToString
strSignupDateEnd = lblEndDate.Text
In both cases, you initialize a new string variable to a value from a DatePicker control, and then immediately overwrite that string variable with a value from a label, such that the initialization from the previous line has no effect.

Related

vb.net option strict on convert string to date

I am trying to convert a string from a database to a Date type with this format "yyyy-M-d"
The string is stored in this format "yyyy-M-d"
So I can execute this code with the Date variables in this format "yyyy-M-d"
Because Option Strict is ON Visual Studio 2019 ver 16.7.5 is UN-happy
If gvTorF = "False" And varToday > varFTue Then
First I am not sure it is necessary but the posts I read about comparing Dates makes this suggestion
Here are my variables
Dim varToday As Date
Dim varFTue As Date
Dim varStr As String
Next I click a Button to get the data from the Database With this code below
Public Sub GetDateInfo()
Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
conn.Open()
Using cmd As SQLiteCommand = New SQLiteCommand($"SELECT * FROM DateInfoTable WHERE DID = '1'", conn)
Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
While rdr.Read()
varTorF = rdr("ditORf").ToString
'varFTue = CDate(rdr("diTESTdate")) 'shows as 10/26/2021
'varFTue = Date.ParseExact(varStr, "yyyy-M-d", provider As IFormatProvider, As Date)
'Tried line of code above this can NOT format correct
varTESTdate = CType(rdr("diTESTdate"), String) 'shows as 2021-10-26
End While
rdr.Close()
End Using
End Using
End Using
End Sub
Other than turning Option Strict OFF or just use the format "M-d-yyyy" to run my test
Where varToday > varFTue which seems to work
The Question is what are my other options to make the conversion from String to Date?
The function below will convert the two Strings varTESTdate & varTodayStr
The varTESTdate is from the database and varTodayStr is created in the function bothDates
Here is the Function and the call made behind a Button Click event
bothDates(varTESTdate, varTodayStr)
Public Function bothDates(ByVal varTESTdate As String, ByVal varTodayStr As String) As Object
result1 = Date.ParseExact(varTESTdate, "yyyy-M-d", provider:=Nothing)
Dim dateToday = Date.Today
varTodayStr = dateToday.ToString("yyyy-M-d")
result2 = Date.ParseExact(varTodayStr, "yyyy-M-d", provider:=Nothing)
Return (result1, result2)
End Function
You appear to have the conversion in your code already
Dim d = DateTime.ParseExact("2026-10-26", "yyyy-M-d", Nothing) 'or provide a culture instead of Nothing..
Though I'm not sure what the trailing "As IFormatProvider, As Date" is there for
'varFTue = Date.ParseExact(varStr, "yyyy-M-d", provider As IFormatProvider, As Date)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This is a syntax error in this context in vb, and looks like a remnant artifact of a conversion from C# where we use "as X" to perform casts. Don't assume that converters get all code perfect all the time; you nearly always have to fix up their output, especially if pasting in only parts of a program where they can't see all the declared variables (your code appears to not contain provider as a variable)

Textbox format into Datetime?

I had a problem manipulating the textbox. This is the date format 2019-10-10 05-21-27 and I was about to convert it using datetime. But it seems it cannot be Format like this 2019-10-10 05:21:27 I tried several codes for this one but it did not work.
Here is my code:
Dim d As Date = Date.ParseExact(tbox_dateofS.Text, "d/M", CultureInfo.InvariantCulture)
tbox_dateofS.Text = d.ToString("dd/MM/yy hh:mm:ss")
i tried this one also:
tbox_dateofS.Text = Cdate(node.SelectSingleNode("starttime").InnerText).Tostring("yyyy-mm/dd hh:mm:ss"
And I got this error : System.FormatException: 'String was not recognized as a valid DateTime.'
Of course it can be formatted like that. You simply need to specify the correct format to convert FROM in order to get a Date that you can then format however you want.
Imports System.Globalization
Module Module1
Sub Main()
Dim text = "2019-10-10 05-21-27"
Dim dt As Date
If Date.TryParseExact(text, "yyyy-MM-dd HH-mm-ss", Nothing, DateTimeStyles.None, dt) Then
Console.WriteLine(dt.ToString("yyyy-MM-dd HH:mm:ss"))
Else
Console.WriteLine("Invalid input")
End If
Console.ReadLine()
End Sub
End Module
It works exactly as you should expect.
That said, why use a TextBox in the first place? In most cases, you can use a DateTimePicker and it will handle all the formatting and validation for you.
05-21-27 is a bad format (WITH FORMAT STYLE "d/M") to convert in a time object.
So if you don’t want to change your INPUT format use the method below as a workaround otherwise in order to have a correct date Object you need to change your time input string in 05:21:27 and after to format this date in your style again as you want.
Private Function getFormatedDate(sDate As String, Optional formatString As String = "yyyy-MM-dd HH:mm:ss")
Dim correctDateString As String = ""
For i As Integer = 0 To sDate.Length - 1
If IsNumeric(CChar(sDate(i))) OrElse sDate(i) = " " Then
correctDateString &= sDate(i)
Else
If i < 10 Then
correctDateString &= "/"
Else
correctDateString &= ":"
End If
End If
Next
Return Strings.Format(CDate(correctDateString), formatString)
End Function
Usage:
Dim mCorrectDateString As String = getFormatedDate("2019-10-10 05-21-27")

'System.InvalidCastException in Microsoft.VisualBasic.dll'

I have done a little bit of research on different posts and have come to the conclusion that my code as shown below:
Public Class Form1
Private Sub btnGetTime_Click(sender As Object, e As EventArgs) Handles btnGetTime.Click
getTime.ShowDialog()
lblTime.Text = DateAdd(DateInterval.Second, 0, CDate(lblTime.text))
End Sub
End Class
has an error at 'CDate(lblTime.text)'. Now I've not much of a clue what most of this code means. I suppose that's how VB works, do now learn later. The problem is that I can't convert string: lblTime.text to a date format using cDate? why not? I'm using cDate()?
The error reads:
System.InvalidCastException: 'Conversion from string "Label1" to type 'Date' is not valid.'
SOLUTION:
The problem was with a maskedtextbox, I had a string inside of it as a preview. The issue came from converting that string into a date.
It should be:
You are trying to convert a string to date. You can use Convert.ToDateTime function for that.
lblTime.Text = "2018-11-05"
Dim date as Date = Convert.ToDateTime(lblTime.Text)
date.ToString("yyyy-MM-dd"); //to convert back to string.
If your date has a custom format, take a look at DateTime.ParseExact so you can also specify the format.
You can read about it here.
If your date is in this format, 11/05/2018,
lblTime.Text = "11/05/2018"
Dim dt as Date = DateTime.ParseExact(lblTime.Text, "MM/dd/yyyy", Nothing)
date.ToString("yyyy-MM-dd"); //to convert back to string
Custom Date and Time Format Strings

VB .NET comparing strings

I don't get what's going on. The method equals doesn't work, and neither comparing the strings with the '=' operator or with 'string.compare'. thetruth is always set as "false".
Public Function ProcessLabel(myValue As Object) As String
If ((myValue Is DBNull.Value) = False) Then
Dim thetruth As Boolean
Dim myValueStr As String
myValueStr = CStr(myValue)
thetruth = String.Equals(myValueStr, "01/01/1900")
End If
Return myValue.ToString
End Function
I cannot attach images but I assure you, in myValueStr I have "01/01/1900".
I'm pretty sure that myValue is a Date object and not a string and that a database is involved where the minimum value is 01/01/1900, for example the SMALLDATETIME datatype. If you look at it in debugger you see it like 01/01/1900. But if you execute ToString( internally used on CStr(myValue)) you get the localized representation including the time portion, so something like 01.01.1900 00:00:00 (f.e. in germany).
Instead compare the right types:
If Not myValue Is DBNull.Value AndAlso Not myValue Is Nothing Then
Dim date = DirectCast(myValue, Date)
If date = New Date(1900, 01, 01) Then
End If
End If

Migration from vba to vb.net - correct logic for using Iserror

I'm trying to use this code:
If Not IsError(Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT"))) Then
MyString = "'" & Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT")).ToString("yyyy-MM-dd") & "'"
Else
'Do something else
End If
My goal is to assign value to "MyString" only if "Convert.ToDateTime" gives a valid value but the code doesn't do that: It stops when the String isn't recognized as a valid DateTime instead of execute the "else" code.
You should use DateTime.TryParse:
https://msdn.microsoft.com/en-us/library/9h21f14e%28v=vs.110%29.aspx
If you don't know exactly what is the format in which you receive your string then you need to provide a set of possible formats to the DateTime.TryParseExact.
This example below is a simplified test version of your code above
Sub Main
Dim dateConverted as DateTime
Dim testDate = "asdfasldka:08/05/2015 13:10"
Dim yourWannaBeDate = testDate.Substring(testDate.IndexOf(":") + 1).Trim()
Dim possibleFormats = new string() {"d/M/yyyy", "d/M/yyyy H:m", "d/M/yy", "d/M/yy H:m"}
if DateTime.TryParseExact(yourWannaBeDate, possibleFormats, CultureInfo.CurrentCulture, DateTimeStyles.None, dateConverted) then
Console.WriteLine(dateConverted.ToString("yyyy-MM-dd"))
else
Console.WriteLine("Not a date")
End if
End Sub
The above code will match "08/05/2015", "8/5/2015", "08/05/15" and the same strings with the time part in two or one digit format
The trick consists in passing an array of possible formats that could be used to interpret the date in your CurrentCulture (I am assuming that your PC has the culture that match the formats above, however, if this is not the case just initialize a new CultureInfo variable and use it in the TryParseExact)
I wanna thank Leonardo for the tip. This is the code I successfully used:
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture("it-IT")
Dim DateResult As DateTime
Dim styles As DateTimeStyles = DateTimeStyles.None
Dim mTmpDate As String
mTmpDate = DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim()
If DateTime.TryParse(mTmpDate, culture, styles, DateResult) Then
MyString = "'" & DateResult.ToString("yyyy-MM-dd HH:mm") & "'"
Else
'Do something else
End If
The code works with any kind of date in "italian style" and in "MyString" I get a date/time formatted as mySql needs (for a timestamp field).