Different date time format of the user causing an error - vb.net

My application is giving an error on different installation based on their different date/time format which my codes are based on
for example below original code ;
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DTPTarihSec.ValueChanged
Dim BaslangicTarihi As Date
Dim BitisTarihi As Date
BaslangicTarihi = "16/04/1996" 'TCMB kayıtları en eski bu tarihe kadar
BitisTarihi = Date.Today
If hatasayac = False Then
SecilenTarih = DTPTarihSec.Value
End If
hatasayac = False
If (SecilenTarih > BitisTarihi) Then
MsgBox("İleri tarihli kur bilgileri bulunmamaktadır. Lütfen uygun bir tarih giriniz. " & vbCrLf & vbCrLf &
"Kurların geçerli olduğu en son tarihe yönlendirildiniz !", vbOKOnly + vbInformation, "TCMB Döviz Kurları")
hatasayac = True
If Now.DayOfWeek.ToString = "Cumartesi" Or Now.DayOfWeek.ToString = "Saturday" Then
SecilenTarih = Date.Today.AddDays(-1)
DTPTarihSec.Value = Date.Today.AddDays(-1)
ElseIf Now.DayOfWeek.ToString = "Pazar" Or Now.DayOfWeek.ToString = "Sunday" Then
SecilenTarih = Date.Today.AddDays(-2)
DTPTarihSec.Value = Date.Today.AddDays(-2)
Else
SecilenTarih = Date.Today
DTPTarihSec.Value = Date.Today
End If
End If
is giving following error on one of the user computer ;
Unhandled exception has occurred in your application... If you click Quit, the application will close immediately.
Conversation from string "16/04/1996" by type 'Date' is not valid.
This is because of the following code line ;
BaslangicTarihi = "16/04/1996" 'TCMB kayıtları en eski bu tarihe kadar
BitisTarihi = Date.Today
If hatasayac = False Then
SecilenTarih = DTPTarihSec.Value
End If
but it is not giving error on my computer.
My question is about ;How to handle this error which will prevent all different date and time format on different computer

Don't use string to populate a date variable, use a date.
Dim BaslangicTarihi = New Datetime(1996, 04, 16)
I would suggest you turn Option Strict On.
Also, you should properly use the enum for DayOfWeek instead of the string.
If Now.DayOfWeek = Day​OfWeek.Saturday Then

Related

Can I use the same text file in two separate forms within the same project?

I'm working on a computer science project and I'm in the prototype stage right now. I will eventually switch this entire thing to a database once everything for it is sorted on the campus computers but for now I'm using text files. It's written on visual studio using VB (Required by my college). I'm trying to use the same text file in two different forms at different times but I keep getting the same error when I run it, saying that the file is open elsewhere. I assume this is because it reads from that file in the next form but I have made it so that the file isn't even opened until a specific button click on that other window. It reaches this error when I attempt to write data to the file from the first window, I never get to the stage where I read from the file in the next form.
Context:
It's a booking system for a youth hostel, the booking text file is written to, from the booking page and saved. This opens up a booking confirmation page where data is read from the last line of the file and necessary information is taken out (Name, checkin/checkout dates, booking reference etc.) to be inserted into the booking confirmation message so it's sort of tailored to each booking but keeps the same structure. I have a button to "save booking" which would write the data to the file but this is where the error occurs. The other form isn't open, the text file isnt open anywhere else and after writing to the file, it's closed.
Is there a workaround? should I just try using variables to hold the input data to use it in the next form? I'm not too worried about it being perfect because this is just a prototype until my college sorts out its issue with databases but I'd still like it to function the way I want it to.
Thank you :)
From booking page:
Private Sub btnBook_Click(sender As Object, e As EventArgs) Handles btnBook.Click
Dim NewBooking As Bookings
Dim errorFlag As Boolean
Dim bookingID As Integer
errorFlag = False
If txtID.Text = "" Or drpNumGuests.Text = "Please Select" Or txtCheckin.Text = "" Or txtCheckout.Text = "" Or txtRoomNo.Text = "" Then
errorFlag = True
End If
If errorFlag = True Then
MsgBox("Error with data entered, please try again.")
Else
Dim sw As New System.IO.StreamWriter("Bookings.txt", True) 'fix
Dim Booking() As String = File.ReadAllLines("bookings.txt")
If UBound(Booking) < 0 Then
bookingID = 0
Else
bookingID = Str(Int(Booking(UBound(Booking)).Substring(0, 8)) + 1) 'Automatic BookingID assignment
End If
NewBooking.GuestID = LSet(txtID.Text, 9)
NewBooking.BookingID = LSet(bookingID, 9)
NewBooking.Name = LSet(txtName.Text, 25)
NewBooking.GuestNum = LSet(drpNumGuests.Text, 2)
NewBooking.CheckIn = LSet(txtCheckin.Text, 11)
NewBooking.CheckOut = LSet(txtCheckout.Text, 11)
NewBooking.RoomNum = LSet(txtRoomNo.Text, 3)
NewBooking.Requests = txtRequests.Text
sw.WriteLine(NewBooking.GuestID & NewBooking.BookingID & NewBooking.Name & NewBooking.GuestNum & NewBooking.CheckIn & NewBooking.CheckOut & NewBooking.RoomNum & NewBooking.Requests)
FileClose()
MsgBox("Booking complete")
End If
End Sub
Private Sub btnConfirm_Click(sender As Object, e As EventArgs) Handles btnConfirm.Click
Booking_Confirmation.Show()
Me.Hide()
From booking confirmation page:
Private Sub btnGen_Click(sender As Object, e As EventArgs) Handles btnGen.Click
Dim Bookconfirm() As String = File.ReadAllLines("bookings.txt")
Dim Name As String
Dim CheckIn As String
Dim CheckOut As String
Dim NumGuests As String
Dim RoomNum As String
Dim ID As String
Dim BookingID As String
Dim Count As Integer = UBound(Bookconfirm)
ID = Mid(Bookconfirm(Count), 1, 8)
BookingID = Mid(Bookconfirm(Count), 10, 8)
Name = Mid(Bookconfirm(Count), 19, 25)
CheckIn = Mid(Bookconfirm(Count), 46, 10)
CheckOut = Mid(Bookconfirm(Count), 57, 10)
NumGuests = Mid(Bookconfirm(Count), 44, 2)
RoomNum = Mid(Bookconfirm(Count), 68, 2)
txtConfirmation.Text = ID & " Thank you " & Name & " for booking your stay with us. Your booking of " & NumGuests & " has been made for " & CheckIn & "to " & CheckOut & "
We look forward to your arrival. Your booking ID is:" & BookingID
End Sub
Here's an alternate version you can try. As suggested by Hursey in the comments, a Using statement will make sure the file is completely closed and released.
bookingID = 0
Dim lastLine As String = File.ReadAllLines("bookings.txt").LastOrDefault()
If Not IsNothing(lastLine) Then
bookingID = Str(Int(lastLine.Substring(0, 8)) + 1) 'Automatic BookingID assignment
End If
NewBooking.GuestID = LSet(txtID.Text, 9)
NewBooking.BookingID = LSet(bookingID, 9)
NewBooking.Name = LSet(txtName.Text, 25)
NewBooking.GuestNum = LSet(drpNumGuests.Text, 2)
NewBooking.CheckIn = LSet(txtCheckin.Text, 11)
NewBooking.CheckOut = LSet(txtCheckout.Text, 11)
NewBooking.RoomNum = LSet(txtRoomNo.Text, 3)
NewBooking.Requests = txtRequests.Text
Using sw As New System.IO.StreamWriter("Bookings.txt", True)
sw.WriteLine(NewBooking.GuestID & NewBooking.BookingID & NewBooking.Name & NewBooking.GuestNum & NewBooking.CheckIn & NewBooking.CheckOut & NewBooking.RoomNum & NewBooking.Requests)
End Using
MsgBox("Booking complete")
If all of the information is already in NewBooking then either PASS that to the secondary form, or simply move it's declaration out to FORM level so that it's accessible. Then you won't need to read the file again to retrieve the information you literally just had?...

Word VBA- On error go to msgbox rather than crashing userform

How would I incorporate "on error" into my code so that if a user enters something into a textbox that is not a date formatted to MM/DD/YYYY or left blank it will not exit out of my userform. Other solutions are appreciated as well!
The code:
Private Sub CommandButton1_Click()
Dim s As String
s = Me.TextBoxx25.Text
If s = "" Then
ElseIf DateDiff("d", Me.TextBoxx25.Text, "11/12/2020") > 0 Then
Doc1.Bookmarks("bmrow1").Range.Cells.Delete
Doc2.Variables("TextBoxx25").Value = Me.TextBoxx25.Text
Doc2.Variables("TextBoxx1").Value = Me.TextBoxx1.Text
Doc2.Variables("TextBoxx7").Value = Me.TextBoxx7.Text
Doc2.Variables("TextBoxx13").Value = Me.TextBoxx13.Text
Doc2.Variables("TextBoxx19").Value = Me.TextBoxx19.Text
Doc2.Variables("TextBoxx31").Value = Me.TextBoxx31.Text
Else
Doc1.Variables("TextBoxx25").Value = Me.TextBoxx25.Text
Doc1.Variables("TextBoxx1").Value = Me.TextBoxx1.Text
Doc1.Variables("TextBoxx7").Value = Me.TextBoxx7.Text
Doc1.Variables("TextBoxx13").Value = Me.TextBoxx13.Text
Doc1.Variables("TextBoxx19").Value = Me.TextBoxx19.Text
Doc1.Variables("TextBoxx31").Value = Me.TextBoxx31.Text
Doc2.Bookmarks("bmrow1").Range.Cells.Delete
End If
It would have to display a msgbox that says please format as (MM/DD/YYYY)

Finding difference and Comparing dates in VBA

I am trying to write a code that takes in a date as input and checks whether or not it is later than the date defined in the code.
Sub times()
Dim d1 As Date
n = Application.InputBox("Enter a date in mm/dd/yyyy format: ")
entered_date = CDate(entered_date)
d1 = 5 / 11 / 2021
If d1 > entered_date Then
d2 = DateDiff("D", d1, entered_date)
MsgBox ("late by " & d2)
Else
MsgBox ("on time")
End If
End Sub
the date diff function doesn't seem to be working for me or something is wrong my logic.
thanks in advance!
Well here is my answer. And as #NicholasHunter says, Option Explicit is always better!
It is clear that you figure it out, but consider this answer, anyway hope to help someone else.
Option Explicit
Sub times()
'Here you can validate the format date type for your system...
Dim SystemDateType As Integer
Dim SysFormatDate As String
' 0 = m-d-y
' 1 = d-m-y
' 2 = y-m-d
If Application.International(xlDateOrder) = 0 Then
SystemDateType = 0
SysFormatDate = "mm/dd/yyyy"
ElseIf Application.International(xlDateOrder) = 1 Then
SystemDateType = 1
SysFormatDate = "dd/mm/yyyy"
ElseIf Application.International(xlDateOrder) = 2 Then
SystemDateType = 2
SysFormatDate = "yyyy/mm/dd"
End If
'Of course you can do this:
'SystemDateType = Application.International(xlDateOrder)
'Or just use a Select Case...
'But just want to be clear and set the variable SysFormatDate
Dim StopedByUser As String: StopedByUser = "StopedByUser"
'Here you can define your own message.
Dim d1 As Date
'Look for the DateSerial function
Dim d2 As Variant
'This could be Long, but just want to set a data type
Dim ErrHandler As Integer
Dim n As Variant
'Or maybe String?
Dim entered_date As Date
'alwayes respect Data Types...
RetryInput:
n = Application.InputBox("Enter a date in " & SysFormatDate & " format: ")
'The user input...
'Cancel...
If n = False Then
MsgBox StopedByUser
End
End If
'Error Handler!
If IsDate(n) Then 'If the user input a real date...
entered_date = CDate(entered_date)
d1 = DateSerial(2011, 11, 16) ' ==> YYYY, MM, DD
'It is always better to use DateSerial!
'And hard coded... Well hope is just your for the question.
'd1 = 5 / 11 / 2021
If d1 >= entered_date Then
'The >= and <= are better in this case...
d2 = DateDiff("D", d1, entered_date)
MsgBox ("late by " & Abs(d2)) 'Abs return the absolute value, instead -321 return 321.
Else
MsgBox ("on time")
End If
Else 'If the user don't know what is a date...
'ask the user... want to try again...
ErrHandler = MsgBox("Please enter a formated date (" & SysFormatDate & ")", vbDefaultButton1 + vbYesNo, "Retry")
If ErrHandler = 7 Then '7 is NO
MsgBox StopedByUser
End
ElseIf ErrHandler = 6 Then '6 is YES and go back in the code to...
GoTo RetryInput
End If
'Check for MSGBOX here: https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/msgbox-function
End If
End Sub

How to refresh win forms using vb.net?

I am working for application register form and I would like to know when the user opens the register form I need to check if the current date is true or not and when the user tries to change the system date he should pop up message.So I would like to refresh the form for every second and find whether he has changed the date or not.
How do I do that?
Here is my code:
btnRegister.Enabled = False
Dim oReg As Microsoft.Win32.RegistryKey
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey(kstrRegSubKeyName)
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\" & kstrRegSubKeyName)
Dim strOldDay As String = oReg.GetValue("UserSettings", "").ToString
Dim strOldMonth As String = oReg.GetValue("operatingsystem", "").ToString
Dim strOldYear As String = oReg.GetValue("GUID", "").ToString
Dim strRegName As String = oReg.GetValue("USERID", "").ToString
Dim strRegCode As String = oReg.GetValue("LOCALPATH", "").ToString
Dim strCompID As String = oReg.GetValue("CompID", "").ToString
Dim strTrialDone As String = oReg.GetValue("Enable", "").ToString
oReg.Close()
'If the keys should automatically be created, then create them.
If strOldDay = "" Then
CreateRegKeys(txtPassPhrase.Text)
End If
'If the keys are encrypted, decrypt them.
'If EncryptKeys = True Then
strOldDay = Decrypt(txtPassPhrase.Text, strOldDay)
strOldMonth = Decrypt(txtPassPhrase.Text, strOldMonth)
strOldYear = Decrypt(txtPassPhrase.Text, strOldYear)
'End If
'Define global variables.
mintUsedTrialDays = DiffDate(strOldDay, strOldMonth, strOldYear)
'Fill the progress bar
lblApplicationStatus.Text = DisplayApplicationStatus(DiffDate(strOldDay, strOldMonth, strOldYear), mintTrialPeriod)
'Disable the continue button if the trial is over
If DiffDate(strOldDay, strOldMonth, strOldYear) > mintTrialPeriod Then
'unregbutton.Enabled = False
mblnInTrial = False
btnRemind.Enabled = False
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey(kstrRegSubKeyName)
oReg.SetValue("Enable", "1")
oReg.Close()
End If
If strOldMonth = "" Then
Else
Dim dtmOldDate As Date = New Date(Convert.ToInt32(strOldYear), Convert.ToInt32(strOldMonth), Convert.ToInt32(strOldDay))
If Date.Compare(DateTime.Now, dtmOldDate) < 0 Then
'lblApplicationStatus.Text = DisplayApplicationStatus(mintTrialPeriod, mintTrialPeriod)
lblApplicationStatus.Text = "The system clock has been manually changed, and the application has been locked out to prevent unauthorized access!"
End If
End If
'If the trial is done then disable the button
If strTrialDone = "1" Then
mblnInTrial = False
btnRemind.Enabled = False
lblApplicationStatus.Text = "The system clock has been manually changed, and the application has been locked out to prevent unauthorized access!"
End If
'See if the user is already registered, if so re-process the info and check if the computer is all okay.,
If strRegName = "" Then
Else
Dim strRN As String = Decrypt(txtPassPhrase.Text, strRegName)
Dim strRC As String = Decrypt(txtPassPhrase.Text, strRegCode)
Dim UserName As String = strRegName
UserName = UserName.Remove(16, (UserName.Length - 16))
If UserName = Decrypt(txtPassPhrase.Text, strRegCode) Then
If Encrypt(txtPassPhrase.Text, cHardware.GetMotherBoardID.Trim.ToString) = strCompID Then
mblnInTrial = False
mblnFullVersion = True
strRC = strRC.Insert(4, "-")
strRC = strRC.Insert(8, "-")
strRC = strRC.Insert(12, "-") 'Add dashes to make it look cool
lblApplicationStatus.Text = "Licensed version to " + strRN + " with the key " + strRC
txtVKClientName.Enabled = False
txtKeyToValidate.Enabled = False
txtVKClientName.Text = strRN
txtKeyToValidate.Text = strRC
btnRemind.Text = "Registered"
frmMain.Text = "Aquamark v1.2(Registered)"
btnRegister.Hide()
Me.Close()
frmMain.Show()
oReg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software", True)
oReg = oReg.CreateSubKey(kstrRegSubKeyName)
oReg.SetValue("Enable", "")
oReg.Close()
End If
End If
End If
NO, you don't have to "refresh the form for every second and find whether he has changed the date or not. How do I do that", the solution is a lot easier
The windows will send a message to all applications when the data is changed. Listen to that message instead and whenever the data changed do what you want to do so:
//C# sorry I don't know VB but the code is simple and you should convert it without any problem
private DateTime _lastSystemClockChanged = DateTime.MinValue;
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case 0x1E://the time is changed.
//to avoid receiving duplicate notification about time changed
if (_lastSystemClockChanged.AddSeconds(1) < DateTime.Now ||
_lastSystemClockChanged > DateTime.Now)
{
_lastSystemClockChanged = DateTime.Now;
//do what ever you want to do when time changed. note you should
//not call a methods that will block here because of you will block
//this message from arriving to other applications then
}
break;
}
base.WndProc(ref m);
}
You could subscribe to the SystemEvents.TimeChanged event, which is fired when the user changes the time on the system clock. Don't forget to detach the event handler when the form closes as this is a static event.
You could store a date in a field and compare the new date to it when the system time is changed, or just disable the app when the event occurs.

VB.Net Converting from string to double

I have a bad bug in my program where if a user presses the check(calculate) button when there is no input in the textbox the program displays this error: "Conversion from string "" to type 'Double' is not valid." I would like to resolve this but I am not sure how to do the conversion. I was thinking possibly CType but I am hearing talk of parsing. How do I go about this? the textbox is called mskTxtInput and the button object is called btnCheck which does all the calculation and processing.
Update: This is my code except the parsing method so hope this helps a little!
Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click
pic1.Visible = False 'hide picture
pic1.Image = My.Resources.A
pic2.Image = My.Resources.F
Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) = Then
MsgBox("parsing success") ' parsing worked, so use the value in here
Else
MsgBox("parsing failed") ' parsing failed, so alert the user to that fact
End If
If radAdd.Checked = True Then
totalNum = num1 + num2
End If
If radSub.Checked = True Then
totalNum = num1 - num2
End If
If radMulti.Checked = True Then
totalNum = num1 * num2
End If
If mskTxtInput.Text = totalNum Then
lblAns.Text = ("Correct!")
lblAns2.Text = ("Answer is " & totalNum)
pic1.Visible = True
wins = wins + 1
nScore = wins
Else
lblAns.Text = ("Incorrect")
lblAns2.Text = ("Answer should be " & totalNum)
pic2.Visible = True
End If
attempts = attempts + 1
If attempts = 5 Then
MessageBox.Show("Game Finished! ", "End Of Game", _
MessageBoxButtons.OK, _
MessageBoxIcon.Exclamation)
lblAns.Text = ("You scored " & wins & " Out of 5")
btnSpin.Enabled = False
pic1.Visible = False
pic2.Visible = False
lblAns2.Text = ""
lblAns2.Text = "Play again?"
btnCheck.Enabled = False
btnNew.Enabled = True
attempts = 0
wins = 0
End If
mskTxtInput.Clear()
mskTxtInput.Focus()
End Sub
Try using Double.TryParse Method (String, Double) rather
Something like
Dim s As String
Dim result As Double
Dim returnValue As Boolean
returnValue = Double.TryParse(s, result)
Use the TryParse method to do the parsing to avoid getting an exception if the parsing fails:
Dim value As Double
If Double.TryParse(mskTxtInput.Text, value) Then
' parsing worked, so use the value in here
Else
' parsing failed, so alert the user to that fact
End If
dim iVar as integer
dim sStr as string
sstr=""
ivar = val(sstr)
Use the static method Double.TryParse(). If it returns true then parsing was successful, and you can proceed with the operation. If it returns false then parsing was not successful, and you should show an error message (using MessageBox if you desire) and abort the operation.