Crystal report Formula Error String is required - vb.net

I am working in crystal reports and I have created two parameters named startDate and endDate and when I go to Formula selection and I write the code and save it I got an error message "string is required"
the code is:
if {Employees.DateField} >={?startDatePF} and {Employees.DateField}<={?endDate} then true
Please tell me how can I resolve this error.
Public Sub GetReport()
Dim rpt As New CrystalReport1
rpt.Load(Application.StartupPath & "\CrystalReport1.rpt")
Dim pfield As New ParameterField
Dim pfields As New ParameterFields
Dim pdescrete As New ParameterDiscreteValue
Dim pfield1 As New ParameterField
Dim pfields1 As New ParameterFields
End Sub

Related

Insert & receive picture from ms access query db vb.net

so, I want to insert a picture to my ms-access DB and it works fine.
inserting code :
Dim ms As New System.IO.MemoryStream
Dim bmpImage As New Bitmap(GunaPictureBox1.Image)
bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
bytImage = ms.ToArray()
ms.Close()
Dim d As New DBConnect
d.Editdata(String.Format("INSERT INTO TeachersTable (TeacherFN, TeacherLN, [TeacherImage]) values('{0}','{1}','{2}')", GunaTextBox1.Text, GunaTextBox2.Text, bytImage))
display code :
Dim dt As DataTable = New DBConnect().selectdata(String.Format("SELECT [TeachersTable.TeacherImage] FROM TeachersTable where TeachersTable.ID= {0}", 1))
Dim EditTeacher As New EditTeacher
Dim pictureData As Byte() = DirectCast(dt.Rows(0)(1), Byte())
Dim stream As New IO.MemoryStream(pictureData)
EditTeacher.GunaPictureBox1.Image = Image.FromStream(stream)
EditTeacher.Show()
but now I want to display it on a picture box but when I execute the code its shows me an error said "Parameters is not valid" & I don't know where is the problem!

Remove the time in Datagridview and when exported to PDF

Please help me guys!
I want the time in Date_Purchased(date) to be removed in datagridview. Because whenever I exported the datagrid in PDF, it has the date and time in it. I only want the date and remove the time especially when exported to PDf.
Here's the sample piece of code.
Public Sub NewInventory()
Dim NI as SqlCommand =con.CreateCommand
NI.CommandText = "Insert into Items_table(Room_ID, PC_Number, Item_Name, Date_Purhased) VALUES (#Room_ID,#PC_Number, #Item_Name, #Date_Purchased);"
NI.Parameters.AddWithValue("#Room_ID", Room_ID)
NI.Parameters.AddWithValue("#PC_Number", PC_Number)
NI.Parameters.AddWithValue("#Item_Name", Item_Name)
NI.Parameters.AddWithValue("#Date_Purchased", DatePurchasedDTP.Value)
NI.ExecuteNonQuery()
MessageBox.Show("New item created.")
End Sub
//for DataGridView
Public Sub GetRoomItems(RoomID As String)
Dim getItems As String = "Select Item_ID, PC_Number,
Item_Name, Date_Purchased WHERE Room_ID=" + RoomID
Dim adapter As New SqlDataAdapter(getItems, connection)
Dim table As New DataTable()
adapter.Fill(table)
InventoryDataGrid.DataSource = table
End Sub
//For exporting to pdf
Private Sub ExportButton_Click(sender As Object, e As EventArgs) Handles ExportButton.Click
connection.Close()
connection.Open()
Dim pdfTable As New PdfPTable(ReportDataGridView.ColumnCount)
pdfTable.DefaultCell.Padding = 1
pdfTable.WidthPercentage = 100
pdfTable.DefaultCell.HorizontalAlignment = Element. ALIGN_CENTER
Dim ptable As New Font(iTextSharp.text.Font.FontFamily.HELVETICA, 11, iTextSharp.text.Font.BOLD, BaseColor.BLACK)
For Each column As DataGridViewColumn in ReportDataGridView.Columns
Dim cell as new PdfPCell(New Phrase(New Chunk(column.HeaderText, ptable)))
cell.HorizontalAlignment = Element.ALIGN_CENTER
cell.FixedHeight = 30
pdfTable.AddCell(cell)
Next
For Each row as DataGridViewRow In ReportDataGridView.Rows
For each cell as DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString)
Next
Next
Dim folderpath As String = "C:\PDFs\"
If Not Directory.Exists(folderpath) Then
Directory.CreateDirectory(folderpath)
End If
Using sfd as New SaveFileDialog()
sfd.ShowDialog()
sfd.OverWritePrompt = True
sfd.Title =" Save As"
sfd.AddExtension = True
sfd.DefaultExt = ".pdf"
Using stream As New FileStream(sfd.FileName & ".pdf",
FileMode.Create)
Dim pdfdoc As New Document (PageSize.LETTER, 36.0F, 36.0F,36.0F,36.0F)
PdfWriter.GetInstance(pdfdoc.stream)
pdfdoc.Open()
pdfdoc.Add(pdfTable)
pdfdoc.Close()
stream.Close()
If File.Exists("path") Then
File.AppendAllText("path", "contents")
End If
pdfdoc.Close()
stream.Close()
End Using
End Using
End Sub
If you would ask me what's the data type of Date_Purchased, it is date. I used date not datetime. And still confused why the time is still in pdf whenever I exported it.
Please help me! Thank you so much
In .NET a Date still has a time component, it's just set to midnight (e.g. 12:00:00). You can read about this here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netframework-4.8
A new object with the same date as this instance, and the time value
set to 00:00:00 midnight (00:00:00).
If you want to display a Date as a string with only the date, you can use Date.ToString() and specify a format which omits the time such as Date.ToString("dd/MM/yyyy"). Alternatively you can use Date.ToShortDateString() which does this but uses the current culture short date string format.
More info here: https://learn.microsoft.com/en-us/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.8
In your code you are doing this loop:
For Each row as DataGridViewRow In ReportDataGridView.Rows
For each cell as DataGridViewCell In row.Cells
pdfTable.AddCell(cell.Value.ToString)
Next
Next
If you change this to use the underlying DataTable instead of the DataGridView itself you can use the DataColumn.DataType to check when you're using a date:
For Each row as DataRow In DataTable.Rows
For Each item In row.ItemArray
If item.GetType Is GetType("System.DateTime") Then
pdfTable.AddCell(item.ToString("dd/MM/yyyy"))
Else
pdfTable.AddCell(item.Value.ToString)
End If
Next
Next
I'm a bit rusty on the specifc syntax but you should be able to work it out from there.

NullReferenceException was unhandled by user code - declaring Excel.Worksheet object

I'm transitioning from Excel VBA to VB.NET, so if this is a dumb question, please go easy on me. I get a NullReferenceException was unhandled by user code on this line of the following sub:
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
VS says that the Object reference is not set to an instance of the object. I'm not sure why it's asking for that, because I've already declared a new instance of Excel in the objApp variable. Why would I need to declare a new instance of each object under that class? It's very possible I'm not thinking about that correctly, but I just wanted to mention my thoughts. Overall, I'm just trying to test the sub below to see if it will open and close a connection to a PostgreSQL database.
Imports Microsoft.Office.Interop
Public Sub QueryData(ByVal ribbonUI As Office.IRibbonControl)
Dim objApp As New Excel.Application
Dim objBook As Excel.Workbook = objApp.ActiveWorkbook
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
Dim pgconn As String
pgconn = "Driver={PostgreSQL};" &
"Server = localhost;" &
"Port = 5432;" &
"Database = CFABudget;" &
"Uid = postgres;" &
"Pwd = budgeto;"
Dim SQL As String = objSheet.Range("BudgetSQL").Text
Dim conn As New Data.Odbc.OdbcConnection(pgconn)
Dim cmd As Data.Odbc.OdbcCommand = New Data.Odbc.OdbcCommand(SQL)
conn.Open()
MsgBox("Success!", vbOKOnly)
conn.Close()
End Sub
Thank you all for your help!
Replace
Dim objApp As New Excel.Application
With:
Dim objApp As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
You were trying to get active workbook from new empty instance of excel.

Retrieve data from excel file to make charts using the visual basic

I'm fairly new to Visual Basic. I'm using the Visual Studio 2013 and MS Excel 2010. I would like to program a code with VB that can retrieve information from the Excel .xlsx file and using that information to make charts.
Here's the edited version:
Imports System.Reflection
Imports Excel = Microsoft.Office.Interop.Excel
'Add reference Assemblies, Framework, System.Windows.Forms.DataVisualization
'Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim excelApp As Excel.Application
Dim excelWB As Excel.Workbook
Dim excelWS As Excel.Worksheet
Dim FNameRng As Excel.Range
Dim AveRng As Excel.Range
Dim AveCLRng As Excel.Range
Dim AveUCLRng As Excel.Range
Dim FNameArry As New ArrayList()
Dim AveArry As New ArrayList()
Dim AveCLArry As New ArrayList()
Dim AveUCLArry As New ArrayList()
excelApp = CreateObject("Excel.Application")
excelApp.Visible = False
'Open the Workbook
excelWB = excelApp.Workbooks.Open("C:\Users\Joesph\Documents\Charts\Control Limit\18x17 - 10 mil stop.xlsx")
excelWS = excelApp.Sheets("18x17 - 10 mil stop")
'Set the Range for File Name
FNameRng = excelWS.Range("A2", excelWS.Range("A2").End(Excel.XlDirection.xlDown))
'Set the Range for Average Data
AveRng = excelWS.Range("B2", excelWS.Range("B2").End(Excel.XlDirection.xlDown))
AveCLRng = excelWS.Range("H2", excelWS.Range("H2").End(Excel.XlDirection.xlDown))
AveUCLRng = excelWS.Range("I2", excelWS.Range("I2").End(Excel.XlDirection.xlDown))
'Store Range as Array
FNameArry.Add(FNameRng.Value)
AveArry.Add(AveRng.Value)
AveCLArry.Add(AveCLRng.Value)
AveUCLArry.Add(AveUCLRng.Value)
Me.CenterToScreen()
Me.WindowState = FormWindowState.Maximized
Chart1.Titles.Add("Title1")
Chart1.Titles(0).Text = "Average"
Chart1.Titles(0).Font = New Font("Garamond", 24, FontStyle.Bold)
Chart1.Series("Series1").XValueMember = "FNameArry"
Chart1.Series("Series1").YValueMembers = "AveArry"
Chart1.Series("Series1").YValueMembers = "AveCLArry"
Chart1.Series("Series1").YValueMembers = "AveUCLArry"
End Sub
End Class
So, I store the Excel range into an arraylist. I used the array as the Chart points. The program now can run without any error, but it display nothing other than the chart title. What did I do wrong here? Do I have to loop the array for the chart to display the X and Y axis? Any help would be appreciated. Thank you!
Here it is. I am using the OLE db driver to get data out of xlsx instead of Interop. I am also using 3 series instead of a single one with multiple Y values.
Imports System.Windows.Forms.DataVisualization.Charting
Imports System.Data
Imports System.Data.OleDb
'The Excel file name
Dim fileName As String = "YourExcelData.xlsx"
'connection string for Xlsx files - Microsoft ACE OLEDB 12.0
'Connect to Excel 2007 (and later) files with the Xlsx file extension.
'That is the Office Open XML format with macros disabled.
' "HDR=Yes;" indicates that the first row contains columnnames, not data.
'"HDR=No;" indicates the opposite.
'"+fileNameString+" remove String from it as defind above
Dim sConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+fileNameString+";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Dim myConnection As New OleDbConnection(sConn)
myConnection.Open()
' The code to follow uses a SQL SELECT command to display the data from the worksheet.
' Create new OleDbCommand to return data from worksheet.
' change range
Dim myCommand As New OleDbCommand("Select * From [data1$A2:I2500]", myConnection)
' create a database reader
Dim myReader As OleDbDataReader = myCommand.ExecuteReader (CommandBehavior.CloseConnection)
' Populate the chart with data in the file
' can also use Chart.DataBindTable
Chart1.Series(0).Points.DataBindXY(myReader, "FNameArry", myReader, "AveArry")
Chart1.Series(1).Points.DataBindXY(myReader, "FNameArry", myReader, "AveCLArry")
Chart1.Series(2).Points.DataBindXY(myReader, "FNameArry", myReader, "AveUCLArry")
' close the reader and the connection
myReader.Close()
myConnection.Close()

crystal report viewer The Parameter is incorrect

i tried to pass parameter to crystal report viewer. but it show The Parameter is incorrect.
Dim rpt As New ReportDocument
rpt.FileName = My.Application.Info.DirectoryPath & "\MAuditList.rpt"
Dim paramDV As New ParameterDiscreteValue()
paramDV.Value = frmMachine.machine
rpt.ParameterFields("#mchno").CurrentValues.Clear()
rpt.ParameterFields("#mchno").DefaultValues.Clear()
rpt.ParameterFields("#mchno").CurrentValues.Add(paramDV)
paramDV.Value = frmMachine.batch - 1
rpt.ParameterFields("#batch").CurrentValues.Clear()
rpt.ParameterFields("#batch").DefaultValues.Clear()
rpt.ParameterFields("#batch").CurrentValues.Add(paramDV)
paramDV.Value = InpStdPt
rpt.ParameterFields("#Points").CurrentValues.Clear()
rpt.ParameterFields("#Points").DefaultValues.Clear()
rpt.ParameterFields("#Points").CurrentValues.Add(paramDV)
paramDV.Value = OvrPoints
rpt.ParameterFields("#ovrpt").CurrentValues.Clear()
rpt.ParameterFields("#ovrpt").DefaultValues.Clear()
rpt.ParameterFields("#ovrpt").CurrentValues.Add(paramDV)
Form1.CrystalReportViewer1.ReportSource = rpt
Form1.Show()</code>
any error in these code??
You should assign the parameters to your Report object and then assign the report object to your CrystalReportViewer.
Try something like this:
'Create report object and load the report
Dim rpt As New ReportDocument()
rpt.FileName = My.Application.Info.DirectoryPath & "\MAuditList.rpt"
'Set the Parameters
Dim paramDV As New ParameterDiscreteValue()
paramDV.Value = "Parameter Value"
rpt.ParameterFields("#ParameterName").CurrentValues.Clear()
rpt.ParameterFields("#ParameterName").DefaultValues.Clear()
rpt.ParameterFields("#ParameterName").CurrentValues.Add(paramDV)
'Assign the report object to the Viewer Report Source
Form1.CrystalReportViewer1.ReportSource = rpt
Form1.Show()