Crystal Report Always prompting for Date Parameter - vb.net

I am currently having a problem whilst passing date parameters from vb.net to Crystal Report XI
I have written a number of reports and have never had a problem whilst passing a parameter, but having said that this is the first time that I have passed a date
It appears to completely ignore the parameters that I am passing and continually asks me to enter a start date(SDate) and end date(EDate)
here is my code
Public Sub GenerateInvoiceByDate(ByVal SDate As Date, ByVal EDate As Date, ByVal boolByAccount As Boolean, ByVal strAccountRef As String)
Dim strSelectionText As String = ""
Dim theReport As New ReportDocument
theReport.FileName = strReportLocation & "Invoice2.rpt"
theReport.SetParameterValue("SDate", Format(SDate, "dd/MM/yyyy"))
theReport.SetParameterValue("EDate", Format(EDate, "dd/MM/yyyy"))
theReport.SetParameterValue("AccountRef", strAccountRef)
If boolByAccount = True Then
'generate an invoice for a specific customer account between two dates
strSelectionText = "{InvoiceHeader.CustomerRef}= {?AccountRef} and {InvoiceHeader.CreatedOn} in {?SDate} to {?EDate}"
Else
'generate all invoices between two dates
strSelectionText = "{InvoiceHeader.CreatedOn} in {?SDate} to {?EDate}"
End If
theReport.RecordSelectionFormula = strSelectionText
theReport.SetDatabaseLogon(strDatabaseUser, strDatabasePassword)
ReportView.CRView.ReportSource = theReport
ReportView.ShowDialog()
End Sub
I was assuming that the problem was with the format of the date that Crystal reports was expecting, hence i introduced that Format() method. I have confirmed that crystal is expecting a date and not date time. The two dates are passed to the method via the following code
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
CropTrackMod.GenerateInvoiceByDate(dtpSDate.Value, dtpEDate.Value, chkByAccount.Checked, txtAccountRef.Text)
End Sub
I am starting to run out of ideas and would appreciate anyone who can shed light on my problem.
Thanks in advance guys
UPDATE:
I have now changed my code as follows. If i set a start date and end date then it works OK. When i attempt to set an account ref when boolaccount = true i get the prompt for "AccountRef". I just cant understand why it keeps loosing that one value.
here is my updated code
'Test Sub for adding parameter fields to crystal reports dynamicly
Public Sub TESTGenerateInvoiceByDate(ByVal SDate As DateTime, ByVal EDate As DateTime, ByVal boolByAccount As Boolean, ByVal strAccountRef As String)
Dim strSelectionText As String = ""
Dim theReport As New ReportDocument
theReport.FileName = strReportLocation & "Invoice2.rpt"
'theReport.Load(strReportLocation & "Invoice2.rpt")
ReportView.CRView.ReuseParameterValuesOnRefresh = True
If boolByAccount = True Then
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", strAccountRef.ToUpper.ToString)
'theReport.SetParameterValue("Changed", "True")
'theReport.SetParameterValue("InvoiceRef", "")
'theReport.SetParameterValue("New", "True")
'generate an invoice for a specific customer account between two dates
strSelectionText = "{InvoiceHeader.CustomerRef} = {?AccountRef} and {InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
Else
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", "")
'theReport.SetParameterValue("AccountRef", strAccountRef)
'theReport.SetParameterValue("Changed", "True")
'theReport.SetParameterValue("InvoiceRef", "")
'theReport.SetParameterValue("New", "True")
'generate all invoices between two dates
strSelectionText = "{InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
End If
theReport.RecordSelectionFormula = strSelectionText
ReportView.CRView.ReportSource = theReport
theReport.SetDatabaseLogon(strDatabaseUser, strDatabasePassword)
'ReportView.CRView.Refresh()
ReportView.ShowDialog()
End Sub
If i insert a breakpoint at the end of the sub on the showdialog i can see that the "HasRecords" property of the report document has a value of "HasRecords = {"Missing parameter values."}"
I have confirmed in the report designer that there are only 3 parameter fields
I can confirm that if i enter a value manually when the report viewer prompts the report does work.

I am glad to say that i have now resolved the problem i was having above
it was due to the order in which i was setting properties of the Report Document
I needed to supply the record select formula prior to setting the parameter values
my working code is as follows
Public Sub GenerateInvoiceByDate(ByVal SDate As DateTime, ByVal EDate As DateTime, ByVal boolByAccount As Boolean, ByVal strAccountRef As String)
Dim strSelectionText As String = ""
Dim theReport As New ReportDocument
theReport.FileName = strReportLocation & "Invoice2.rpt"
'theReport.Load(strReportLocation & "Invoice2.rpt")
ReportView.CRView.ReuseParameterValuesOnRefresh = True
If boolByAccount = True Then
'generate an invoice for a specific customer account between two dates
strSelectionText = "{InvoiceHeader.CustomerRef} = {?AccountRef} and {InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
theReport.RecordSelectionFormula = strSelectionText
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", strAccountRef.ToUpper.ToString)
theReport.SetParameterValue("Changed", "True")
theReport.SetParameterValue("InvoiceRef", "")
theReport.SetParameterValue("New", "True")
Else
'generate all invoices between two dates
strSelectionText = "{InvoiceHeader.CreatedOn} >= {?SDate} and {InvoiceHeader.CreatedOn} <= {?EDate}"
theReport.RecordSelectionFormula = strSelectionText
theReport.SetParameterValue("SDate", SDate)
theReport.SetParameterValue("EDate", EDate)
theReport.SetParameterValue("AccountRef", "")
theReport.SetParameterValue("AccountRef", strAccountRef)
theReport.SetParameterValue("Changed", "True")
theReport.SetParameterValue("InvoiceRef", "")
theReport.SetParameterValue("New", "True")
End If
ReportView.CRView.ReportSource = theReport
theReport.SetDatabaseLogon(strDatabaseUser, strDatabasePassword)
'ReportView.CRView.Refresh()
ReportView.ShowDialog()
End Sub
Good luck and tanks to all that helped

You probably are passing string values to a date parameter.
change this line :
theReport.SetParameterValue("SDate", Format(SDate, "dd/MM/yyyy"))
with:
theReport.SetParameterValue("SDate", SDate)

Related

Different date time format of the user causing an error

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

VBA function cannot return value to main sub

I have a problem:
Now I got a date range for a main sub (20160706-20160805) and I have to separate the value and put it as a date. What I do is:
Main sub date ()
Dim strDaterage as string
Dim startdate as date
'For the sake of simplicity, just use the hard code for the date
strDaterange = "20160706-20160805"
startdate = findstartdate()
msgbox (startdate)
End sub
And for the function to separate the date an extract the value:
Function findstartdate()
daterange = "20160706-20160805"
startDateange = Left(daterange, 8)
startYear = Left(startDateange, 4)
startMonth = Mid(startDateange, 5, 2)
startDay = Right(startDateange, 2)
startdate = DateSerial(startYear, startMonth, startDay)
End Function
I try using the byval and byfer but it still does not work. How can I return the date value back into the main sub?
Many thanks in advance!
Not sure why you are using a String as an input, but if you want you can use the code below (there are more efficient ways to do it).
Your Sub :
Sub SubDate()
Dim strDaterage As String
Dim startdate As Date
strDaterage = "20160706-20160805"
startdate = findstartdate(strDaterage)
MsgBox (startdate)
End Sub
Your function:
' need to add a String variable as an input, and return tha value as a Date
Function findstartdate(DateRange As String) As Date
startDateange = Left(DateRange, 8)
startYear = Left(startDateange, 4)
startMonth = Mid(startDateange, 5, 2)
startDay = Right(startDateange, 2)
startdate = DateSerial(startYear, startMonth, startDay)
' convert the string result to a Date
findstartdate = CDate(startdate)
End Function

VB form load event based on date

I'm attempting to display a button on a secondary form in vb based on what the date is (Trying to get a reset button to show only on the last day of the year).
I've tried a few different things with the code below...
I originally put it in the Form Load Event of Form 2, no msgbox displayed, button didn't display.
I cut the code out of my project and pasted it into the Form Load Event of a new project to test it on it's own... Msgbox displayed and button displayed!! :)
This got me thinking maybe I had to put the code into the Form Load Event of the Main Form. I pasted it there and made the modifications to point to form2 (Current version of the code)....
Once again , no msgbox, no button
What am I missing?
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim date1 As String = String.Format("{0:MM/dd/yyyy}", DateTime.Now)
Dim todaysdate As String = Format(Now, "Long Date")
Dim dayofweek = todaysdate.Substring(0, todaysdate.IndexOf(","))
Dim year As String = Now.Year
Dim datecheck As String = "12/29/"
Dim datecheck1 As String = "12/30/"
Dim datecheck2 As String = "12/31/"
' Add Current Year to Date to Check variables
datecheck = datecheck + year
datecheck1 = datecheck1 + year
datecheck2 = datecheck2 + year
Dim expenddt As Date = Date.ParseExact(date1, date1, System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt1 As Date = Date.ParseExact(datecheck, datecheck,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt2 As Date = Date.ParseExact(datecheck1, datecheck1,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
Dim expenddt3 As Date = Date.ParseExact(datecheck2, datecheck2,
System.Globalization.DateTimeFormatInfo.InvariantInfo)
' If DEC 29 or 30 Falls Fiday, Display Reset Button
If date1 = datecheck And dayofweek = "Friday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!")
Form2.Reset.Visible = True
End If
If date1 = datecheck1 And dayofweek = "Friday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!!")
Form2.Reset.Visible = True
End If
' If it's Dec 31 and it's Not Saturday or Sunday, Display Reset Button
If date1 = datecheck2 and dayofweek <> "Saturday" and dayofweek <> "Sunday" Then
' MsgBox Used Only For Testing
MsgBox("THIS ONE WORKED!!!")
Form2.Reset.Visible = True
End If
End Sub
First things first, have a read through the documentation for the DateTime structure. You can do everything that you're trying to do without using Strings. The DateTime structure has a DayOfWeek property, and Month and Day properties that will help you here.
Secondly, the way you are using the ParseExact method is wrong (not that you should end up using it). The second parameter to the ParseExact method is the format string that you expect the date to be in (something like "MM/dd/yyyy"). Passing in a formatted date will not work, and from my experiments, will simply return the current date without any parsing occurring.
So, with all that in mind (and assuming you want to show the button on the last weekday in the year as your code suggests, and not just the last day in the year as your question stated), try something like this:
Private Sub Main_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Form2.Reset.Visible = ShouldShowResetButton(DateTime.Now)
End Sub
Private Function ShouldShowResetButton(currentDate As DateTime) As Boolean
Return GetLastWeekdayInYear(currentDate.Year) = currentDate.Date
End Function
Private Function GetLastWeekdayInYear(year As Integer) As Date
Dim lastDayInYear As Date
lastDayInYear = New Date(year, 12, 31)
Select Case lastDayInYear.DayOfWeek
Case DayOfWeek.Sunday
Return New Date(year, 12, 29)
Case DayOfWeek.Saturday
Return New Date(year, 12, 30)
Case Else
Return lastDayInYear
End Select
End Function

How to Calculate the difference between two dates

I have this code:
Private Sub CalculateBUT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateBUT.Click
If SelectTheDateComboBox.Text = "Calculate the difference between two dates" Then
FromYearTextBox.Text = FromDateTimePicker.Value.Year
FromMonthTextBox.Text = FromDateTimePicker.Value.Month
FromDayTextBox.Text = FromDateTimePicker.Value.Day
ToYearTextBox.Text = ToDateTimePicker.Value.Year
ToMonthTextBox.Text = ToDateTimePicker.Value.Month
ToDayTextBox.Text = ToDateTimePicker.Value.Day
Dim DaysMyString, MonthsMyString, YearsMyString As String
Dim DaysDifferance, MonthsDifferance, YearsDifferance As Long
DaysMyString = FromDateTimePicker.Value.Day
MonthsMyString = FromDateTimePicker.Value.Month
YearsMyString = FromDateTimePicker.Value.Year
DaysDifferance = DateDiff(DateInterval.Day, ToDateTimePicker.Value.Day, CDate(DaysMyString))
MonthsDifferance = DateDiff(DateInterval.Month, ToDateTimePicker.Value.Month, CDate(MonthsMyString))
YearsDifferance = DateDiff(DateInterval.Year, ToDateTimePicker.Value.Year, CDate(YearsMyString))
DifferenceTextBox2.Text = DaysDifferance & "Days, " & MonthsDifferance & "Months, " & YearsDifferance & "Years"
End Sub
and my problem in the picture below :
so, i need some help please.
You want DateDiff to give you the number of days between two dates and you want DaysDifference to hold the result, and that's fine:
DaysDifferance = DateDiff(DateInterval.Day, x, y)
But for this to work x and y need to be dates.
When you take ToDateTimePicker.Value (which is a date) and add .Day on the end it's no longer date.
So you want:
DaysDifferance = DateDiff(DateInterval.Day, ToDateTimePicker.Value, CDate(DaysMyString))

Validating a date in a textbox

I am trying to valid user input in a textbox which will only takes dates or an empty value (hence the textbox vs a date time picker). Here are the conditions:
Only a date value ("dd-mm-yyyy" or "dd-mm-yy)
Must contain only slashes or numbers
The date has to be on the day it is being typed in
This is what I have so far:
Private Sub tbApp1_TextChanged(sender As System.Object, e As System.EventArgs) Handles tbApp1.TextChanged
If Not Me.tbApp1.Text = String.Empty Then
If Not DateTime.TryParseExact(tbApp1.Text.Trim, formats, New Globalization.CultureInfo("en-US"), Globalization.DateTimeStyles.None, dtTemp) Then
If Not tbApp1.Text.Trim = DateTime.Today.Date Then
ErrorProvider1.SetError(tbApp1, "This is not a valid date; Enter in this format ('M/d/yyyy' or 'M/d/yy')")
End If
Else
ErrorProvider1.Clear()
End If
ElseIf Me.tbApp1.Text.Trim = "" Then
ErrorProvider1.Clear()
End If
End Sub
Masked Textbox use
'Private Sub mtbApp1_TypeValidationCompleted(ByVal sender As Object, ByVal e As TypeValidationEventArgs) Handles mtbApp1.TypeValidationCompleted
If Not Me.mtbApp1.Text = String.Empty Then
If (Not e.IsValidInput) Then
ErrorProvider1.SetError(mtbApp1, "The data you supplied must be a valid date in the format mm/dd/yyyy.")
Else
' Now that the type has passed basic type validation, enforce more specific type rules.
Dim UserDate As DateTime = CDate(e.ReturnValue)
If (UserDate = DateTime.Now) Then
ErrorProvider1.SetError(mtbApp1, "The data you supplied must be today's date")
e.Cancel = True
End If
End If
ErrorProvider1.Clear()
End If
End Sub'
I noticed for a date like 03/18/2014 when it loaded back into the masked textbox it converts to 31/82/014. How could i fix this? The query pulls back the field as
CONVERT(VARCHAR(10),Date,101) AS Date
I set it in vb as :
Dim Approval1 As Date = Nothing
and then
If Not IsDBNull(((WorklistsDS.Tables(0).Rows(0).Item("Approval1")))) Then
Approval1 = ((WorklistsDS.Tables(0).Rows(0).Item("Approval1")))
End If
and then loaded into the masked textbox as:
If Approval1 <> Nothing Then
Me.mtbApp1.Text = Approval1
End If
You could also simplify your validation with
If IsDate(tbApp1.Text) Then
'valid date now just check if date falled within permitted range
Dim CompDate As Date = CDate(tbApp1.Text)
Dim MidDate As Date = *enter your min date here*
Dim MaxDate As Date = *enter your max date here*
If CompDate >= MinDate AndAlso CompDate <= MaxDate Then
'Date is within permitted range
......
Else
'Date outside range
'Display error
End If
Else
'text in tbApp1 is not a date
'Display Error
End If