'System.InvalidCastException in Microsoft.VisualBasic.dll' - vb.net

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

Related

Trying to ADD numbers to a string

I want to add some numbers to a string in this code. But I don't know how can I do it without getting the following error:
System.InvalidCastException: 'Conversion from string "Happy Holidays!!! " to type 'Double' is not valid.' Internal Exception. FormatException: Input string was not in a correct format.
I don't want to SUM, I want to ADD. Here's the code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Day = Now.Day
Dim Month = Now.Month
Dim Year = Now.Year
Label1.Text = MonthName(Now.Month, True) //not necessary
If Now.Month = 12 Then
Me.Text = "Happy Holidays!!!" + " " + Day + "/" + Month + "/" + Year 'here's the problem
End If
End Sub
End Class
While the + operator can be used to concatenate Strings, it should not be used. The reason is because of situations like this where the compiler will attempt to treat the + as an addition operator instead of the String concatenation operator.
You have a couple of options:
Use the & operator
Use String interpolation
You can also simply call the ToString method on your DateTime object and pass in the desired format rather than getting the day, month, and year and passing them individually.
Take a look at this example:
Dim rightNow = DateTime.Now
Label1.Text = rightNow.ToString("MMMM")
If (rightNow.Month = 12) Then
Me.Text = $"Happy Holidays!!! {rightNow:d/M/yyyy}"
End If

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")

datetime variable with extra hour and custom format as datetime not string

This is so simple but i am not able to figure out how to do it, please excuse my ignorance.
I would like a datetime variable to be current datetime + 1 hour in the format "yyyy-mm-dd HH:mm:ss"
I have tried this so far (dotnetfiddle.net) and when i assign it to the datetime variable the date is changed to slashes instead of hypen.
Imports System
Public Module Module1
Public Sub Main()
Dim tet As String = Datetime.Now.AddHours(1).ToString("yyyy'-'MM'-'dd hh:mm:ss")
Dim expiryTime As DateTime = DateTime.ParseExact("2009-05-08 14:40:52,531", "yyyy-MM-dd HH:mm:ss,fff",
System.Globalization.CultureInfo.InvariantCulture)
Console.WriteLine(convert.todatetime(tet))
Console.WriteLine(tet)
Console.WriteLine(Datetime.Now.AddHours(1))
End Sub
End Module
As per one of the comments I have used parseExact and i still see the date with slashes instead of hypen
When you convert tet back to a DateTime it will display as the default pattern. Keep it as a string for display. The convert it back with ParseExact when you need to use it as DateTime again.
Dim dNow As DateTime = DateTime.Now.AddHours(1)
Dim strNow As String = dNow.ToString("yyyy-MM-dd hh:mm:ss")
Console.WriteLine(strNow)

SQL in VB.net showing wrong dates

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.

DateTime.TryParse fails for perfectly valid dates

I've read this string from a file: 23/07/1998. This is a perfectly valid date string. It has no ambiguity, given those numbers there (appears) to be only one possible way to parse it.
DateTime.TryParse, on the other hand, tells me its invalid. I suspect this is due to my culture settings.
TryParse has variations that are rather complex, so I'm wondering if there's an easy way to parse this with "dd/MM/yyyy"?
TryParse doesn't know if your date is MM/dd/yyyy or dd/MM/yyyy. It's obvious to the observer only because we can deduce from the fact that there is no month 23. But it wouldn't know what 02/03/1998 was.
DateTime.ParseExact(dateString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
Will tell it which format to use.
Dim iString As String = "01/12/1998"
Dim oDate As DateTime = DateTime.ParseExact(iString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)
MsgBox(oDate.ToString())
Like already mentioned by dwilliss the regular DateTime.TryParse() method cannot distinguish between dd/MM and MM/dd, and operates only on a standard set of date time formats. To specify a different format use either DateTime.ParseExact() or DateTime.TryParseExact()
If you want a less annoying syntax you can create an extension method wrapping the DateTime.TryParseExact() method.
Imports System.Globalization
Imports System.Runtime.CompilerServices
Public Module Extensions
<Extension()> _
Public Function TryParseDate(ByVal Input As String, ByVal Format As String, <Out()> ByRef Result As DateTime) As Boolean
Return DateTime.TryParseExact(Input, Format, CultureInfo.InvariantCulture, DateTimeStyles.None, Result)
End Function
End Module
Now you can use it like this:
Dim DateString As String = "23/07/1998"
Dim ResultDate As DateTime = Nothing
If DateString.TryParseDate("dd/MM/yyyy", ResultDate) Then
MessageBox.Show("Success: " & ResultDate.ToString())
Else
MessageBox.Show("Input was not a valid date!")
End If