How To: Change Image visibility on rdlc export - rdlc

I Have an Image in rdlc report.
in the report i set visibility to false
I want that when I Export to PDF or EXCEL
To set the Image visibility to true.
How do I do This?
Is The a way to Catch the Export Event ?
I don`t want to create a custom 'export'.
Thanks …

The only way I found out how to do it was by creating a custom 'export' function...which really is quite simple.
Step 1: Create a parameter in your report called "ShowImage". I used the data type of String, made the prompt hidden and set a default value of "False". That way, when the report first runs in your report viewer on your page, it is not hidden.
Step 2: Change the visibility property for your image to an expression that has the following:
=CBool(Parameters!ShowImage.Value)
Step 3: Hide the Export Controls on your report viewer. Here is my example:
<rsweb:ReportViewer ID="ReportViewer1" runat="server" ShowExportControls="false" Font-Names="Verdana" Font-Size="8pt">
<LocalReport ReportPath="Report1.rdlc" >
</LocalReport>
</rsweb:ReportViewer>
Step 4: Add a button to your page and code the custom export. You will need to be sure to set the parameter you created in step 1.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Create ReportViewer
Dim viewer As New Microsoft.Reporting.WebForms.ReportViewer()
Dim p(0) As Microsoft.Reporting.WebForms.ReportParameter
p(0) = New Microsoft.Reporting.WebForms.ReportParameter("ShowImage", "True")
viewer.LocalReport.ReportPath = Server.MapPath("Report1.rdlc")
viewer.LocalReport.SetParameters(p)
'Export to PDF
Dim reportContent As Byte() = viewer.LocalReport.Render("PDF", Nothing, Nothing, Nothing, Nothing, Nothing, Nothing)
'Return PDF
Me.Response.Clear()
Me.Response.ContentType = "application/pdf"
Me.Response.AddHeader("Content-disposition", "attachment; filename=Report.pdf")
Me.Response.BinaryWrite(reportContent)
Me.Response.End()
End Sub
That's it. May I ask, why didn't you want to create a custom export event?

Related

Cognex Insight SetComment Not Persisting

I have a job that stores cell locations as comments in particular cells, but I'm running into a situation where the CvsInsight::SetComment method is not persisting.
I'm displaying a form as a dialog wherein the user can change the cell locations that are stored in the comment cells and when the user clicks the save button I'm creating a new instance of a custom class, setting the properties to the new cell locations (set by the user), setting the DialogResult as OK, and then closing the form. Then in the form where I called ShowDialog, I call the SetComment method for each property in the custom class on their respective cell.
This is what I'm doing in the dialog's Save button:
Private Sub ButtonSave_Click(sender As Object, e As EventArgs) Handles ButtonSave.Click
' Check if the name, username, password, pass, fail, total, reset, and results are all set
Dim invalidFields As List(Of String) = New List(Of String)()
For Each pair In _requiredFields
If (String.IsNullOrWhiteSpace(DirectCast(Controls.Find(pair.Key, True).FirstOrDefault, TextBox).Text)) Then
invalidFields.Add(pair.Value)
End If
Next
If (invalidFields.Any()) Then
MessageBox.Show($"The following required fields are missing a value: {String.Join(", ", invalidFields)}", "Invalid Form", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
' Set the returned object's values, set the dialog result, and then close the dialog
CameraSettings = New CameraSettings() With {
.FailCell = FailCellLocation.Text,
.FocusCell = FocusCell.Text,
.IsVisible = Visibility.Checked,
.PassCell = PassCellLocation.Text,
.ResetCell = ResetCellLocation.Text,
.ResultsCell = ResultsCellLocation.Text,
.TotalCell = TotalCellLocation.Text
}
DialogResult = DialogResult.OK
Close()
End Sub
And this is what I'm doing in the form that opens the dialog:
Private Sub Settings_Click(sender As Object, e As EventArgs) Handles Settings.Click
Using cameraSettingsDialog As frmCameraSetting = New frmCameraSetting(InsightDisplay.InSight)
With cameraSettingsDialog
If (.ShowDialog = DialogResult.OK) Then
InsightDisplay.InSight.SetComment(New CvsCellLocation(_focusCell), New CvsCellComment(.CameraSettings.FocusCell))
InsightDisplay.InSight.SetComment(New CvsCellLocation(_passCell), New CvsCellComment(.CameraSettings.PassCell))
InsightDisplay.InSight.SetComment(New CvsCellLocation(_failCell), New CvsCellComment(.CameraSettings.FailCell))
InsightDisplay.InSight.SetComment(New CvsCellLocation(_totalCell), New CvsCellComment(.CameraSettings.TotalCell))
InsightDisplay.InSight.SetComment(New CvsCellLocation(_resultCell), New CvsCellComment(.CameraSettings.ResultsCell))
InsightDisplay.InSight.SetComment(New CvsCellLocation(_resetCell), New CvsCellComment(.CameraSettings.ResetCell))
GetSettingCells()
End If
End With
End Using
End Sub
What is happening is that the code executes without throwing any exceptions, but the comment is not set. What's frustrating is that I'm not able to debug because the CvsInsightDisplay's Insight gets set to null anytime I try to access the results in the middle of setting the comment. However, I can verify that the CameraSettings' properties are what I'd expect them to be because if I setup a Console.WriteLine to print the various properties they're right.
Looking through the SDK, I cannot find any documentation as to why it wouldn't set the value without throwing an exception.
For those of you who run into the same issue, the problem resolved around the fact that I was trying to set a cell that was past the maximum row in the job. To fix the issue, I had to change the cells in which I was setting the comments for to ones with a lower row index.
Unfortunately, Cognex does not have this behavior documented in any of their documentation.

Crystal Report formula field index changing on each new build

I've got a Crystal Report which I made in CR2008, which I'm printing from my vb.net application. In this report, I have an image and a formula field.
The image formula (Under Format Graphic > Picture > Graphic Location is set to be the formula field called #imgLocation.
In my vb.net code, I have the following block to select the saved file path from the database, then fill #imgLocation with this value, to set the image that is being shown.
Try
Dim logoPath As String = ds.Tables(0).Rows(0).Item("reportLogoPath") & ""
If logoPath = "" Then
MessageBox.Show("No logo path has been defined in the System Settings. Please set " & _
"one and try again.", "Load Report Failed", MessageBoxButtons.OK)
Exit Sub
Else
cReport.DataDefinition.FormulaFields.Item(2).Text = Chr(34) & logoPath & Chr(34)
End If
Catch ex As Exception
errorLog(ex)
End Try
I've seen this working twice. The image I want replaced the placeholder image when I had FormulaFields.Item(2), but then I resized the image and it didn't work. I then changed the value of the index, and it worked with FormulaFields.Item(4), but again stopped working when I resized the image.
Why is the index changing, and what is the way around it?
I tried using the named parameter option, but FormulaFields.Item("#imgLocation") gave me an error of
Invalid Index
EDIT
As per #Bugs request, this is the report showing the correct string and image
Then, after deleting and re-saving the image (But in a slightly bigger size), the parameter was passed correctly still, but the placeholder image was shown instead.
This makes me think now that it's to do with image size, however, re-sizing it back to the original size still didn't show it again.
EDIT 2
Could it be do to with the fact that I'm loading a new form which contains the report viewer, rather than opening it from the same form?
cReport.RecordSelectionFormula = selectionFormula
Me.Cursor = Cursors.Default
Dim f As New frmReportViewer(con, cReport, 0)
f.Show()
Private Sub frmReportViewer_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
setFormSizes(Me, con)
Me.Location = New Point((Screen.PrimaryScreen.WorkingArea.Width / 2) - (Me.Width / 2), 10)
Me.Text = "Report Viewer"
Dim logOnInfo As New TableLogOnInfo()
Dim i As Integer
For i = 0 To cReport.Database.Tables.Count - 1
logOnInfo.ConnectionInfo.DatabaseName = "comm_db"
logOnInfo.ConnectionInfo.Password = "Acplus2016!"
cReport.Database.Tables.Item(i).ApplyLogOnInfo(logOnInfo)
Next i
cReport.VerifyDatabase()
crViewer.ReportSource = cReport
crViewer.ToolPanelView = CrystalDecisions.Windows.Forms.ToolPanelViewType.None
crViewer.Zoom(87)
Catch ex As Exception
errorLog(ex)
End Try
End Sub
Please note my answer is addressing the part regarding adding parameters. For the moment the no image available placeholder is proving difficult to resolve on my side.
To add a parameter please follow these steps:
Add a parameter within Crystal Reports called imageLocation:
After pressing OK you should have a parameter in your list like this:
The following code will pass a value to the parameter:
Dim cReport As New ReportDocument
cReport.Load("C:\Report.rpt")
If cReport.ParameterFields.Item("imageLocation") IsNot Nothing Then
cReport.SetParameterValue("imageLocation", "\\SAGE200FS\Sage\StockImages\sc002.jpg")
End If
reportViewer.ReportSource = cReport
This is the output (I have added the parameter onto the report):
Note that if you are passing parameters and they are shown on the report, make sure you don't have cReport.VerifyDatabase() in place. This often throws up a dialog box asking for the parameter values.
Screenshot of dialog box:
By not calling cReport.VerifyDatabase() this will stop the dialog box from showing.
Now through Crystal Reports you can set the Graphic Location using a parameter. To do this, add the parameter to the report and suppress the field (as you don't want to see it). Then you can add the Report Field as the location.
Add parameter to report and suppress:
Add Report Field as the Graphic Location for the OLE Object:~=
Run the report and input the parameter. This will change the image accordingly. See both screenshots:
SC001::
INT4303:
This however does not seem to work through VB. The ReportViewer does not handle the change of images. Instead you are left with the default image. I'm unsure why this is the case and I'm guessing it's a bug with Crystal. If anyone knows of why this happens, feel free to comment.
EDIT
After discussing the smaller points in chat, we seem to have worked out that the issue arose because of the file path. Saving it to the database as \\server\...\...\image.png was not displaying, but after changing it to Z:\...\...\image.png it has worked fine every time. It was because of the file path, all along.

Print rdlc report without viewing print dialogue box

I have am writing a POS application, which requires to print invoice very often.
I need to send it directly to printer instead of viewing the print dialogue. Using Reportviewer_renderingcomplete, I can avoid seeing the report but I do not know how to avoid seeing the print dialogue box and print report without user intervention?
Thanks a lot.
Here is how you can do it:
Dim m_currentPageIndex As Integer
Private m_streams As IList(Of Stream)
Dim report As New LocalReport()
report.DataSources.Add(New ReportDataSource("testData", reportData.Tables(0)))
report.ReportEmbeddedResource = "ReportsLibrary.rptTestData.rdlc"
Dim deviceInfo As String = "<DeviceInfo><OutputFormat>EMF</OutputFormat><PageWidth>8.5in</PageWidth><PageHeight>11in</PageHeight><MarginTop>0.25in</MarginTop><MarginLeft>0.25in</MarginLeft><MarginRight>0.25in</MarginRight><MarginBottom>0.25in</MarginBottom></DeviceInfo>"
Dim warnings As Warning()
m_streams = New List(Of Stream)()
report.Render("Image", deviceInfo, CreateStream, warnings)
For Each stream As Stream In m_streams
stream.Position = 0
Next
Dim printDoc As New PrintDocument()
printDoc.PrinterSettings.PrinterName = "<your default printer name>"
Dim ps As New PrinterSettings()
ps.PrinterName = printDoc.PrinterSettings.PrinterName
printDoc.PrinterSettings = ps
printDoc.PrintPage += New PrintPageEventHandler(PrintPage)
m_currentPageIndex = 0
printDoc.Print()
Where PrintPage defined as follows:
' Handler for PrintPageEvents
Private Sub PrintPage(sender As Object, ev As PrintPageEventArgs)
Dim pageImage As New Metafile(m_streams(m_currentPageIndex))
' Adjust rectangular area with printer margins.
Dim adjustedRect As New Rectangle(ev.PageBounds.Left - CInt(ev.PageSettings.HardMarginX), ev.PageBounds.Top - CInt(ev.PageSettings.HardMarginY), ev.PageBounds.Width, ev.PageBounds.Height)
' Draw a white background for the report
ev.Graphics.FillRectangle(Brushes.White, adjustedRect)
' Draw the report content
ev.Graphics.DrawImage(pageImage, adjustedRect)
' Prepare for the next page. Make sure we haven't hit the end.
m_currentPageIndex += 1
ev.HasMorePages = (m_currentPageIndex < m_streams.Count)
End Sub
This is an interesting walkthrough by Microsoft: Printing a Local Report without Preview.
It's a different approach from yours because it prints directly a report without using ReportViewer and RenderingComplete event.
In order to not display PrintDialog box you must set printDoc.PrinterSettings.PrinterName with your default printer name.
Maybe you can store this value in a user configuration file.
It is actually far more simple than you would have imagined.
Within your form, include a "PrintDocument" component from the Toolbox.
Within your code behind, you will want to call the following method on your newly added component.
PrintDoc.Print()
The documentations state that the Print() "Starts the document's printing process". It will automatically begin printing the default set printer.
As tezzo mentioned, to set the Printer manually you can use the following snippet:
PrintDoc.PrinterSettings.PrinterName = "YourPrinterNameHere"
PrintDoc.PrinterSettings.PrinterName "gets or sets the name of the printer to use" as according to documentation. And if you need any further help, check out this video.
Please note however that video does not mention how to print "silently". It is just a good reference for beginners to see how the Print Components work together.

DataGridView losing initial state specified at design time

When I try to change the datasource of my DataGridView, I am loosing the order of the columns and their type(checkboxes,comboboxes) that i specified at design time.
It's like changing the datasource is generating again the datagridview, why ? and How can I change the datasource without losing these information ?
Please if you know give me help
Thanks in advance
On form load i do something like
Private Sub frmGrid_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim Path as string
Path="C:\......Myfile.xml"
Dim oData as dataset
oData = New DataSet
oData.ReadXml(Path)
oData.AcceptChanges()
DataGridView1.DataSource = oData
DataGridView1.DataMember = oData.Tables(0).TableName
end sub
Till now everything is fine the design mode is preserved.
Then I have in my interface I have a button to save the content of my Grid to an excel file (it's an xml, formatted for excel)
Then i want to import this, on a button action, so i do the following
Private Sub Button13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
Dim MyDs As DataSet
MyDs = New DataSet
Dim InputFileStream As New System.IO.FileStream(Path, System.IO.FileMode.Open)
MyDs = ImportExcelXML(InputFileStream, True, True)
MyDs.ReadXml(Path)
MyDs.AcceptChanges()
DataGridView1.DataSource = MyDs
DataGridView1.DataMember = MyDs.Tables(0).TableName
end sub
Probabily you have set up GenerateColums property to "True"
That means the GridView will generate the columns(name and number of them) againts the data sorce.
If the data source (in you case data table) are different it will come up a different grid.
If the datasource are different you can design the layout of your gridView but after that you have to manually bind the data to the columns as you wish.You can do that into
RowDataBound event.
The datatable you are trying to assign to the DataGridView1.DataSource is structured different from the way you defined the DataGridView at design time. Put a break point in your code right before you reassign the new DataTable to the DataSource and see what is different in the structure. It is most likely that you either have more or less DataColumns in place, or the columns could be in a different order. They might even be named different. If at design time you set your DataGridViewColumn's DataProperty to a specific name, than then name needs to be exact.
You'll just have to check it at that breakpoint and see what the differences are.
I found a solution, your hints helped me to look on the right direction to find a solution !
What i was doing was on form load
MaGrille.DataSource = oData
MaGrille.DataMember = oData.Tables(0).TableName
Then in the button click I do :
MaGrille.DataSource = MyDs
MaGrille.DataMember = MyDs.Tables(0).TableName
The problem is that the grid is rebuild and i loose the formatting, column order etc..
After many tests, I understood that It wasn't working because the names of datatables are differents ! I don't understand why, but it was the error as it seems.
I had the following values
oData.Tables(0) = "DECLARATION"
MyDs.Tables(0) = "Sheet1"
So I noticed that if I rename MyDs.Tables(0) by "DECLARATION" instead of "Sheet1", and i click on the button, this time I don't loose formatting, neither orders ...
This inspired me to find the SOLUTION :
After many tries, I realized that if instead of doing on form load
MaGrille.DataSource = oData
MaGrille.DataMember = oData.Tables(0).TableName
and on button click :
MaGrille.DataSource = MyDs
MaGrille.DataMember = MyDs.Tables(0).TableName
I do :
on form load
MaGrille.DataSource = oData.Tables(0)
and on button click
MaGrille.DataSource = MyDs.Tables(0)
All works fine even if the oData.Tables(0).TableName is different from MyDs.Tables(0).TableName !!
I found the solution Now, but still can't understand the WHY If anyone get an explication, please let me know.
Thanks to all again

How do you export an report while using ActiveReports

I'm using Active Reports within my VB program to generate a report based on my data. Right now I have the report opening fine and it is allowing the user to print, copy, find, etc. I am unsure how to add the functionality to let the user choose to export the chart once the program is running.
I've been looking at many tutorials but there is always something that makes it unable to work in my program. For example this forum gives the exact code for what I want as they add an export button to the toolbar and then adds the functionality to the button. Unfortunately I am unable to access the toolbar. They access it with Me.Toolbar and I am unable to access it this way.
Another forum here doesn't add the export to the toolbar and instead inserts it directly into the code but I'm not sure what to import to allow me to do it this way as my project doesn't recognize ActiveReportsPDFExport.ARExportPDF.
UPDATE:
Found a way to export to PDF by adding to the ActiveReport in the design format a DataDynamics.ActiveReports.Export.Pdf.PdfExport and then calling from my code PdfExport1.Export(Me.Document, "D:\Kyra\HELP.pdf")
Problem:
This is called at the end of my function which opens the active report. I want the user to be able to choose to export the report and then be given the option of choosing the format and location where they want to save the report to.
Below is the code to add a PDF Export button to the ActiveReports Toolbar using VB.NET and ActiveReports 6:
Const pdfExportToolID As Long = 42
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myExportTool As DataDynamics.ActiveReports.Toolbar.Button
myExportTool = New DataDynamics.ActiveReports.Toolbar.Button()
myExportTool.ButtonStyle = DataDynamics.ActiveReports.Toolbar.ButtonStyle.Text
myExportTool.Caption = "Export to PDF"
myExportTool.Id = pdfExportToolID
Me.Viewer1.Toolbar.Tools.Add(myExportTool)
' load report:
Dim rpt As New NewActiveReport1()
Me.Viewer1.Document = rpt.Document
rpt.Run(False)
End Sub
Private Sub Viewer1_ToolClick(ByVal sender As System.Object, ByVal e As DataDynamics.ActiveReports.Toolbar.ToolClickEventArgs) Handles Viewer1.ToolClick
If (e.Tool.Id = pdfExportToolID) Then
Dim pdf As New DataDynamics.ActiveReports.Export.Pdf.PdfExport()
pdf.Export(Me.Viewer1.Document, "C:\users\scott\junk\myActiveReport.pdf")
End If
End Sub
This code works inside of a form with an ActiveReports Viewer on hte form named "Viewer1".
Hope this helps,
Scott Willeke
GrapeCity
Just follow along in the instructions here. Specifically, it's the button they add 'cmdExport' that lets the user start the export.
This code working for me, just pass it Webviewer object.
ABC.Run();
ARWebViewer.Report = ABC;
ExportToExcel(ARWebViewer); // call ExportToExcel method,
public void ExportToExcel(DataDynamics.ActiveReports.Web.WebViewer objWebviewer)
{
DataDynamics.ActiveReports.Export.Xls.XlsExport XLSexport = new DataDynamics.ActiveReports.Export.Xls.XlsExport();
System.IO.MemoryStream memStream = new System.IO.MemoryStream();
if (XLSexport == null)
XLSexport = new DataDynamics.ActiveReports.Export.Xls.XlsExport();
XLSexport.AutoRowHeight = true;
XLSexport.MinColumnWidth = (float)0.2;
XLSexport.RemoveVerticalSpace = true;
XLSexport.UseCellMerging = true;
XLSexport.Export(objWebviewer.Report.Document, memStream);
memStream.Position = 0;
Response.ContentType = "application/Xls";
Response.AddHeader("content-disposition", "attachment; filename=" + ajDoc + ".Xls");
Response.BinaryWrite(memStream.ToArray());
Response.End();
XLSexport = null;
}