Fail to open connection #Error Rdlc Custom Code - rdlc

m in a big trouble please help...I have Rdlc report the expression is using custom code which has Connection string but when i run the report it doesnt work :(
the connection is failed to open. this is so far i have done :
My custom Rdlc code here..
Function GradeCal(ByVal SubDivID As Integer, ByVal Perc As Decimal) As String
Dim oConn As New System.Data.SqlClient.SqlConnection
oConn.ConnectionString = "Data Source=*****;Initial Catalog=PSIDB; Persist Security Info=True; User ID=sa; Password=*******"
oConn.Open()
Dim oCmd As New System.Data.SqlClient.SqlCommand
oCmd.Connection = oConn
oCmd.CommandText = "SELECT * from dbo.[funcGradesCal](" + SubDivID + "," + Perc + ")"
Dim nRetVal As String = oCmd.ExecuteScalar()
oConn.Close()
If (nRetVal <> Nothing) Then
Return nRetVal
Else
Return "0-0"
End If
End Function
and here its my my expression...
=Code.GradeCal(1,42)
but it results #Error :(
i have added refernece in custom code..
System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
Please give me any idea

Embedding connection string in custom code will result in deployment nightmares.
A better approach would be to create a report parameter with default value of "0-0", fetch data Dim nRetVal As String = oCmd.ExecuteScalar() at time of calling the report and assign the report parameter with the nRetVal.
Update
Move your function GradeCal() from the report to another class or module
Open your report in design view
Define a report parameter
Select View -> Report Data from the menu
Right click Parameters and click on Add Parameter...
Assign a name to your parameter: GradeCal4.
Optionally set a Default value for the parameter
Modify your report item from =Code.GradeCal(1,42) to =Parameters!GradeCal.Value or just drag and drop the parameter onto the report.
In your program call your function dim nRetVal as integer = GradeCal(1,42) to fetch data
Pass value to parameter report
Dim param As New ReportParameter("GradeCal",nRetVal)
ReportViewer1.LocalReport.SetParameters(param)

Related

How can I change the command text of an SQL connected table in Excel using VBA? [duplicate]

I have an Excel document that has a macro which when run will modify a CommandText of that connection to pass in parameters from the Excel spreadsheet, like so:
Sub RefreshData()
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary")
.OLEDBConnection.CommandText = "Job_Cost_Code_Transaction_Summary_Percentage_Pending #monthEndDate='" & Worksheets("Cost to Complete").Range("MonthEndDate").Value & "', #job ='" & Worksheets("Cost to Complete").Range("Job").Value & "'"
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Refresh
End Sub
I would like the refresh to not only modify the connection command but also modify the connection as I would like to use it with a different database also:
Just like the macro replaces the command parameters with values from the spreadsheet I would like it to also replace the database server name and database name from values from the spreadsheet.
A complete implementation is not required, just the code to modify the connection with values from the sheet will be sufficient, I should be able to get it working from there.
I tried to do something like this:
ActiveWorkbook
.Connections("Job_Cost_Code_Transaction_Summary")
.OLEDBConnection.Connection = "new connection string"
but that does not work. Thanks.
The answer to my question is below.
All of the other answers are mostly correct and focus on modifying the current connection, but I want just wanting to know how to set the connection string on the connection.
The bug came down to this. If you look at my screenshot you will see that the connection string was:
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=ADCData_Doric;Data Source=doric-server5;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=LHOLDER-VM;Use Encryption for Data=False;Tag with column collation when possible=False
I was trying to set that string with ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").OLEDBConnection.Connection = "connection string"
I was getting an error when i was simply trying to assign the full string to the Connection. I was able to MsgBox the current connection string with that property but not set the connection string back without getting the error.
I have since found that the connection string needs to have OLEDB; prepended to the string.
so this now works!!!
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").OLEDBConnection.Connection = "OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=ADCData_Doric;Data Source=doric-server5;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=LHOLDER-VM;Use Encryption for Data=False;Tag with column collation when possible=False"
very subtle but that was the bug!
I think you are so close to achieve what you want.
I was able to change for ODBCConnection. Sorry that I couldn't setup OLEDBConnection to test, you can change occurrences of ODBCConnection to OLEDBConnection in your case.
Try add this 2 subs with modification, and throw in what you need to replace in the CommandText and Connection String. Note I put .Refresh to update the connection, you may not need until actual data refresh is needed.
You can change other fields using the same idea of breaking things up then Join it later:
Private Sub ChangeConnectionString(sInitialCatalog As String, sDataSource As String)
Dim sCon As String, oTmp As Variant, i As Long
With ThisWorkbook.Connections("Job_Cost_Code_Transaction_Summary").ODBCConnection
sCon = .Connection
oTmp = Split(sCon, ";")
For i = 0 To UBound(oTmp) - 1
' Look for Initial Catalog
If InStr(1, oTmp(i), "Initial Catalog", vbTextCompare) = 1 Then
oTmp(i) = "Initial Catalog=" & sInitialCatalog
' Look for Data Source
ElseIf InStr(1, oTmp(i), "Data Source", vbTextCompare) = 1 Then
oTmp(i) = "Data Source=" & sDataSource
End If
Next
sCon = Join(oTmp, ";")
.Connection = sCon
.Refresh
End With
End Sub
Private Sub ChangeCommanText(sCMD As String)
With ThisWorkbook.Connections("Job_Cost_Code_Transaction_Summary").ODBCConnection
.CommandText = sCMD
.Refresh
End With
End Sub
You could use a function that takes the OLEDBConnection and the parameters to be updated as inputs, and returns the new connection string. It's similar to Jzz's answer but allows some flexibility without having to edit the connection string within the VBA code each time you want to change it - at worst you'd have to add new parameters to the functions.
Function NewConnectionString(conTarget As OLEDBConnection, strCatalog As String, strDataSource As String) As String
NewConnectionString = conTarget.Connection
NewConnectionString = ReplaceParameter("Initial Catalog", strCatalog)
NewConnectionString = ReplaceParameter("Data Source", strDataSource)
End Function
Function ReplaceParameter(strConnection As String, strParamName As String, strParamValue As String) As String
'Find the start and end points of the parameter
Dim intParamStart As Integer
Dim intParamEnd As Integer
intParamStart = InStr(1, strConnection, strParamName & "=")
intParamEnd = InStr(intParamStart + 1, strConnection, ";")
'Replace the parameter value
Dim strConStart As String
Dim strConEnd As String
strConStart = Left(strConnection, intParamStart + Len(strParamName & "=") - 1)
strConEnd = Right(strConnection, Len(strConnection) - intParamEnd + 1)
ReplaceParameter = strConStart & strParamValue & strConEnd
End Function
Note that I have modified this from existing code that I have used for a particular application, so it's partly tested and might need some tweaking before it totally meets your needs.
Note as well that it'll need some kind of calling code as well, which would be (assuming that the new catalog and data source are stored in worksheet cells):
Sub UpdateConnection(strConnection As String, rngNewCatalog As Range, rngNewSource As Range)
Dim conTarget As OLEDBConnection
Set conTarget = ThisWorkbook.Connections.OLEDBConnection(strConnection)
conTarget.Connection = NewConnectionString(conTarget, rngNewCatalog.Value, rngNewSource.Value)
conTarget.Refresh
End Sub
I would like to give my small contribute here to this old topic.
If you have many connections in your Excel file, and you want to change the DB name and DB server for all of them, you can use the following code as well:
It iterates through all connections and extracts the connection string
Each connection string is split into an array of strings
It iterates through the array searching for the right connection values to modify, the others are not touched
The it recompose the array into the string and commit the change
This way you don't need to use replace and to know the previous value, and the rest of the string will remain intact.
Also, we can refer to a cell name, so you can have names in your Excel file
I hope it can help
Sub RelinkConnections()
Dim currConnValues() As String
For Each currConnection In ThisWorkbook.Connections
currConnValues = Split(currConnection.OLEDBConnection.Connection, ";")
For i = 0 To UBound(currConnValues)
If (InStr(currConnValues(i), "Initial Catalog") <> 0) Then
currConnValues(i) = "Initial Catalog=" + Range("DBName").value
ElseIf (InStr(currConnValues(i), "Data Source") <> 0) Then
currConnValues(i) = "Data Source=" + Range("DBServer").value
End If
Next
currConnection.OLEDBConnection.Connection = Join(currConnValues, ";")
currConnection.Refresh
Next
End Sub
This should do the trick:
Sub jzz()
Dim conn As Variant
Dim connectString As String
For Each conn In ActiveWorkbook.Connections
connectString = conn.ODBCConnection.Connection
connectString = Replace(connectString, "Catalog=ADCData_Doric", "Catalog=Whatever")
connectString = Replace(connectString, "Data Source=doric-server5", "Data Source=Whatever")
conn.ODBCConnection.Connection = connectString
Next conn
End Sub
It loops every connection in your workbook and change the Connection String (in the 2 replace statements).
So to modify your example:
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").ODBCConnection.Connection = "new connection string"
I assume it is necessary for your to keep the same connection-name? Otherwise, it would be simplest to ignore it and create a new Connection.
You might rename the connection, and create a new one using the name:
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Name = "temp"
'or, more drastic:
'ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").Delete
ActiveWorkbook.Connections.Add "Job_Cost_Code_Transaction_Summary", _
"a description", "new connection string", "command text" '+ ,command type
Afterwards, Delete this connection and reinstate the old connection/name. (I am unable to test this myself currently, so tread carefully.)
Alternatively, you might change the current connections SourceConnectionFile:
ActiveWorkbook.Connections("Job_Cost_Code_Transaction_Summary").OLEDBConnection.SourceConnectionFile = "..file location.."
This typically references an .odc file (Office Data Connection) saved on your system that contains the connection details. You can create this file from the Window's Control Panel.
You haven't specified, but an .odc file may be what your current connection is using.
Again, I am unable to test these suggestions, so you should investigate further and take some precautions - so that you won't risk losing the current connection details.

VB.net connection string works, then doesn't, then does - why?

Using VB.NET, VS 19 v16.10.4
I have a small application which asks a user to provide database server, database name and then builds a connection string. Then, using a data access layer DLL I've written it runs a check to see if a connection can be made to the database.
The problem is unusual:
If I write the connection string direct to the data access layer into a variable it connects;
If I use a string builder to build the string then pass it to the data access layer it fails;
If I write the connection string into a variable then pass it to the data access layer it fails;
If I use the first step again it works.
With DAL
MessageBox.Show("Using hard-coded string")
.ConnectionString = "data source=THEWINELIBRARY\MSSQLSERVER01;initial catalog=TrialDatabase;trusted_connection=true"
.DoConnectionCheck() 'THIS WORKS
MessageBox.Show("Using string builder string")
.ConnectionString = SBConnString.ToString.Trim
.DoConnectionCheck() 'THIS FAILS
MessageBox.Show("Using CS string")
.ConnectionString = CS.Trim
.DoConnectionCheck() 'THIS FAILS
MessageBox.Show("Using hard-coded string")
.ConnectionString = "data source=THEWINELIBRARY\MSSQLSERVER01;initial catalog=TrialDatabase;trusted_connection=true"
.DoConnectionCheck() 'THIS WORKS
End With
The data access layer does the following in the DoConnectionCheck method:
Public Sub DoConnectionCheck()
OpenConnection()
With AppConnection
If (.State = ConnectionState.Open) Then
RaiseEvent ConnectionOpened()
CloseConnection()
End If
End With
End Sub
and the OpenConnection method:
Private Sub OpenConnection()
With AppConnection
'Is the conenction currently closed?
If (.State = ConnectionState.Closed) Then
Try
'Set connection string to POS
.ConnectionString = ConnectionString
'Try opening the connection
.Open()
'Otherwise raise an event.
Catch E As Exception
RaiseEvent ConnectionFailed()
End Try
End If
End With
End Sub
And the connection string is a simple property:
Public ConnectionString As String
So, what I don't understand is why the connection fails with the string builder string and the variable string, but not with the hard-coded string?
If there is any other code you need please let me know, I posted what i think is enough to explain the problem without putting in too much that makes the question unreadable.
here is the code which constructs the connection string from entries in a form:
Dim CS As String = "datasource=" & .TextServer.Text.Trim & ";initial catalog=" & .TextDatabase.Text.Trim & ";trusted_connection=true"
SBConnString = New StringBuilder
With SBConnString
.Clear()
.Append("datasource=")
.Append(Me.TextServer.Text.Trim)
.Append(";initial catalog=")
.Append(Me.TextDatabase.Text.Trim)
.Append(";trusted_connection=true")
End With
When these strings are compared to the hard coded string
DAL.ConnectionString = "data source=THEWINELIBRARY\MSSQLSERVER01;initial catalog=TrialDatabase;trusted_connection=true"
the function returns a value 1, "The first substring follows the second substring in the sort order." according to the documentation.
As far as I can see, these strings are identical but somewhere an additional character must be getting inserted in the form textbox.
Again, any suggestions gratefully received.
All the best,
Dermot
Mea culpa - I had a very simple mistake which I could not see - in the two strings causing the problem I had datasource rather than date source...

VB.net insert .msg file into access database [duplicate]

I'm writing a VB application where I need to store an image in the database. The user selects the image on their computer, which gives me the path as a string. Here's my attempt at it, however I'm getting the error "An INSERT INTO query cannot contain a multi-valued field."
Here is my code:
Dim buff As Byte() = Nothing
Public Function ReadByteArrayFromFile(ByVal fileName As String) As Byte()
Dim fs As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fs)
Dim numBytes As Long = New FileInfo(fileName).Length
buff = br.ReadBytes(CInt(numBytes))
Return buff
End Function
Sub ....
Dim connImg As New OleDbConnection
Dim sConnString As String
Dim cmdImg As New OleDbCommand
sConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Settings.DB & ";Persist Security Info=False;"
connImg = New OleDbConnection(sConnString)
connImg.Open()
cmdImg.Connection = connImg
cmdImg.CommandType = CommandType.Text
If d.slogo <> "" Then
cmdImg.CommandText = "INSERT INTO Logo ( refId, [type], [img] ) VALUES(#refId, #type, #imgBinary)"
cmdImg.Parameters.Add("#refId", OleDbType.Double).Value = refId
cmdImg.Parameters.Add("#type", OleDbType.Double).Value = 0
cmdImg.Parameters.Add("#imgBinary", OleDbType.VarBinary).Value = ReadByteArrayFromFile(PathToImage)
cmdImg.ExecuteNonQuery()
End If
....
End Sub
I've tried searching for other solutions online, but it seems everything I find is VB6 or VBA code. And I know people are going to argue that images should not be stored in the database, but in this case, it is my only option.
Thank-you for any help!
As you have discovered, you cannot use a SQL statement to insert files into an Attachment field in an Access database. You have to use the LoadFromFile() method of an ACE DAO Field2 object. The following C# code works for me. It is adapted from the Office Blog entry here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Access.Dao;
namespace daoConsoleApp
{
class Program
{
static void Main(string[] args)
{
// This code requires the following COM reference in your project:
//
// Microsoft Office 14.0 Access Database Engine Object Library
//
var dbe = new DBEngine();
Database db = dbe.OpenDatabase(#"C:\__tmp\testData.accdb");
try
{
Recordset rstMain = db.OpenRecordset(
"SELECT refId, img FROM Logo WHERE refId = 1",
RecordsetTypeEnum.dbOpenDynaset);
if (rstMain.EOF)
{
// record does not already exist in [Logo] table, so add it
rstMain.AddNew();
rstMain.Fields["refId"].Value = 1;
}
else
{
rstMain.Edit();
}
// retrieve Recordset2 object for (potentially multi-valued) [img] field
// of the current record in rstMain
Recordset2 rstAttach = rstMain.Fields["img"].Value;
rstAttach.AddNew();
Field2 fldAttach =
(Field2)rstAttach.Fields["FileData"];
fldAttach.LoadFromFile(#"C:\__tmp\testImage.jpg");
rstAttach.Update();
rstAttach.Close();
rstMain.Update();
rstMain.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
I did the same thing based off of the above code and the blog entry from here.
Here is my vb.net code which allows me to do an OpenFileDialog and multiple selections and the function will handle storing multiple files just fine. Though I did have to add a reference to my project for Microsoft Office 15.0 Access database engine Object Library to get it to work properly. I think you can go down to 12.0 or 14.0 as well.
Private Sub AddAttachment(ByVal Files() As String)
Const Caller = "AddAttachment"
Dim dbe = New Microsoft.Office.Interop.Access.Dao.DBEngine()
Dim db As Microsoft.Office.Interop.Access.Dao.Database
db = dbe.OpenDatabase(dbPath)
Try
Dim rstMain As Microsoft.Office.Interop.Access.Dao.Recordset
rstMain = db.OpenRecordset("SELECT ID, fieldName FROM tableName WHERE ID = " + (dt.Rows(currentRow).Item("ID").ToString), Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenDynaset)
If (rstMain.EOF) Then
rstMain.AddNew()
rstMain.Fields("ID").Value = 1
Else
For Each value As String In Files
rstMain.Edit()
Dim rstAttach As Microsoft.Office.Interop.Access.Dao.Recordset2
rstAttach = rstMain.Fields("ATTACHMENTS").Value
rstAttach.AddNew()
Dim fldAttach As Microsoft.Office.Interop.Access.Dao.Field2
fldAttach = rstAttach.Fields("FileData")
fldAttach.LoadFromFile(value)
rstAttach.Update()
rstAttach.Close()
Next
rstMain.Update()
rstMain.Close()
End If
Catch ex As Exception
If Err.Number <> 3820 Then
MsgBox(ex.Message)
Else
MsgBox("File of same name already attached", MsgBoxStyle.Critical, "Cannot attach file" & Caller)
MessageBox.Show(ex.Message)
End If
End Try
End Sub
I'm now working on the functions to RemoveAttachments and save files from the attachements field. I'll post those here later.
Another thing to add to this. If your database is encrypted then you will need to add to the OpenDatabase command.
This is the code I used in C# but the VB.NET code will be very similiar.
db = dbe.OpenDatabase(dbPath, false, false,"MS Access;PWD=password");
It took me ages to try and track this down on my own and I will try break down the various parts of the method. The MSDN Article for it can be found here.
1st Argument: dbPath, that's the same as the usage in the original post. The location and filename of the database you want to open.
2nd Argument: false. This is a true/false argument that if true opens the database in Exclusive-Mode. So that only this single program can use it. Most of the time this should be false. Only use exclusive mode if you have to.
3rd Argument: false. This is another true/false argument. This time if it's true then it opens the database in Read-only mode.This means you can only use recordsets to read information and you cannot use the Edit, Add or Delete methods. This can be true or false depending on your needs.
4th Argument: This sets specific properties in how to open the database. In this case. It says to set the Microsoft Access property 'PWD' to 'password'. In this property setting will tell method to open up an encrypted database using the password 'password'. Of course you will need to change "password" to whatever the database's actual password is to open but I'd been hunting this down for a while.
I hope this helps.

Passing Parameter to Crystal Reports XI from Visual Studio 2015

I am running into problems with the passing of parameters to an externally created Crystal Reports XI report from the WinForms application I'm building in Visual Studio 2015 Community Edition. No matter what I try to do, the report doesn't seem to get the value unless I manually select it at the prompt (which shouldn't even be popping up) when the report is being displayed. I'm using the same code I've used in a previous application (although that one was built in VS2008), but I've tried a number of "alternate" versions of the code in my attempts to get this working. Here's the code that I'm currently using:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Module modReports
Private WithEvents DocumentToPrint As New Printing.PrintDocument
Private Sub ShowReport(ByVal LID As Integer, ByVal InHouse As Boolean)
Dim Report As New ReportDocument
Dim ReportParameters As ParameterFieldDefinitions = Nothing
Dim Parameter As ParameterFieldDefinition = Nothing
Dim ApplicationValue As ParameterDiscreteValue = Nothing
Dim ReportValues As ParameterValues = Nothing
Dim ReportViewer As New frmReport
Dim Response As DialogResult = DialogResult.Cancel
PrintingReport = True
Report.Load(CRYSTAL_REPORT_FILE_PATH & "ExampleReport.rpt")
Report.Refresh()
Report.VerifyDatabase()
ReportParameters = Report.DataDefinition.ParameterFields
Parameter = ReportParameters.Item("PrintAll")
ReportValues = New ParameterValues
ApplicationValue = New ParameterDiscreteValue
'Parameter.CurrentValues.Clear()
'ReportValues.Clear()
ReportValues = Parameter.CurrentValues
If LID = 7777 Then
ApplicationValue.Value = True
Else
ApplicationValue.Value = False
End If
ReportValues.Add(ApplicationValue)
Parameter.ApplyCurrentValues(ReportValues)
Response = MessageBox.Show("Do you want to send this report directly to the printer?", "SEND TO PRINTER", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If Response = DialogResult.No Then
With ReportViewer
.rptViewer.ReportSource = Nothing
.rptViewer.ReportSource = Report
.WindowState = FormWindowState.Maximized
.rptViewer.RefreshReport()
' Set zoom level: 1 = Page Width, 2 = Whole Page, 25-100 = zoom %
.rptViewer.Zoom(1)
.rptViewer.Show()
.ShowDialog()
End With
ElseIf Response = DialogResult.Yes Then
Dim SelectPrinter As New PrintDialog
Dim PrinterSelected As DialogResult = DialogResult.Cancel
With SelectPrinter
.Document = DocumentToPrint
.AllowPrintToFile = False
.AllowSelection = False
.AllowCurrentPage = False
.AllowSomePages = False
.PrintToFile = False
End With
PrinterSelected = SelectPrinter.ShowDialog
If PrinterSelected = DialogResult.OK Then
Dim Copies As Integer = DocumentToPrint.PrinterSettings.Copies
Dim PrinterName As String = DocumentToPrint.PrinterSettings.PrinterName
Dim LastPageNumber As Integer = 1
Dim PrintBuffer As String = String.Empty
LastPageNumber = Report.FormatEngine.GetLastPageNumber(New ReportPageRequestContext)
Report.PrintOptions.PrinterName = PrinterName
Report.PrintOptions.PrinterDuplex = DocumentToPrint.PrinterSettings.Duplex
Report.PrintToPrinter(Copies, True, 1, LastPageNumber)
If Copies = 1 Then
PrintBuffer = "Printed " & Copies & " copy of "
Else
PrintBuffer = "Printed " & Copies & " copies of "
End If
If LastPageNumber = 1 Then
PrintBuffer += LastPageNumber.ToString & " page."
Else
PrintBuffer += LastPageNumber.ToString & " pages."
End If
MessageBox.Show("The report was sent to the following printer:" & vbCrLf & " • " & PrinterName & vbCrLf & PrintBuffer, "REPORT PRINTED", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End If
PrintingReport = False
End Sub
End Module
The report itself is built to use an XML file as the data source, which is dynamically created by this application. All of that works normally, and oddly enough, if I send the report directly to the printer, it seems to print correctly without prompting me. It's only a problem when I try to display the report through the CrystalReportViewer object.
Some of the things I've tried without success:
I've tried with and without calling the Clear() methods on the
Parameter.CurrentValues and ReportValues objects.
I've tried moving all of the parameter setting logic to after I set the
ReportSource of the CrystalReportViewer control (rptViewer.ReportSource)
I've tried using alternate Crystal Reports objects (ParameterFields instead of ParameterFieldDefinitions and ParameterField instead of ParameterFieldDefinition).
I've tried removing all of the "complicated" code and just using the SetParameterValue method (i.e., Report.SetParameterValue("PrintAll", True)
I've even tried creating different types of parameter fields in the report itself (String, Boolean, Number) and passing appropriate values for those datatypes.
If I walk through the code, it doesn't appear to error out anywhere, and everything looks like it's working just great until I get to the .rptViewer.RefreshReport() line in the With ReportViewer block. I've verified that all of the parameters and values have only the value I am "selecting" via the application by checking them every step up to that point, and it all looks exactly as I expect it to look.
But the application (via Crystal Reports) continues to prompt me for the value I just passed in the code. If I select the value in that prompt, the report does generate correctly based on the value I select, but no matter what I "pass" in the programming, the prompt always defaults to True.
Does anyone have any suggestions that I may have overlooked for how to get this parameter to correctly pass to the CrystalReportViewer control? Please let me know if you need any additional information or have any questions about what I've set up so far here. Thank you in advance.
Okay, so based on the information I found over on http://www.it-sideways.com/2011/10/how-to-disable-parameter-prompt-for.html, it seems that the RefreshReport method for the CrystalReportViewer control basically wipes out any parameters and/or log on information:
1. ) Do not invoke CrystalReportViewer.RefreshReport Method
This method will refresh the data for the report currently displayed
in the CrystalReportViewer control. The report will prompt for
parameters or logon info is necessary.
So, this method is not needed unless the same
CrystalDecisions.CrystalReports.Engine.ReportDocument object is
reused.
By commenting out that line of the code, I was able to prevent the parameter prompt from being displayed. The only issue I have after making that change is that, even though the zoom level is being set to 1 (page width), and when I run the project the CrystalReportViewer control even shows that it's correctly set in the status bar ('Zoom Factor: Page Width' is displayed), the report itself is not actually zoomed in to the page width.
With the RefreshReport method uncommented, if I manually provided the value for my parameter, it would display the report properly zoomed. If I add the zoom button to the control (.rptViewer.ShowZoomButton = True), I can manually choose the Page Width option, which then correctly "re-zooms" the report to the desired level, but it won't immediately display that way if the RefreshReport method is not called.
Regardless, I can spend some time trying to fight that now, but I finally have it properly setting, passing and displaying the results of my parameter. I hope this helps someone else running into this issue.

How to pass parameters to crystal report from vb.net code

I have created a crystal report (cross tab). I'm not using any dataset, instead I used the wizard in crystal report to call an procedure from my Database schema
(Provider given is Microsoft OLEDB provider for oracle, after which I gave my DB credentials(i.e. schema, username, password) and selected the procedure and selected the columns I wanted to display in the report).
There are 5 parameters that I need to pass it from the front end to generate the report. While viewing the crystal report preview, by giving parameters, the report works fine.
Now i want to pass these 5 parameters from the front end(vb.net) to show the report in the CrystalReportViewer. Please suggest the code to write in aspx.vb file.
(PS:- I did go through other forums and found out some code, but all of them were giving some or the other error, so am posting one so that i can get the code specific to my requirement).
Thanks in advance..
I have gotten the report to work...
I wrote the code below:
Dim RptDocument As New ReportDocument
RptDocument.Load(Server.MapPath("rpt\Report.rpt"))
RptDocument.SetParameterValue("param1", Session("param1"))
RptDocument.SetParameterValue("param2", ddlparam2.SelectedValue)
RptDocument.SetParameterValue("param3", param3.text)
RptDocument.SetParameterValue("param4", param4.text)
RptDocument.SetParameterValue("param5", param5.text)
'Set login info
Dim myLogin As CrystalDecisions.Shared.TableLogOnInfo
Dim myTable As Table
For Each myTable In RptDocument.Database.Tables
myLogin = myTable.LogOnInfo
myLogin.ConnectionInfo.ServerName = "server name"
myLogin.ConnectionInfo.DatabaseName = ""
myLogin.ConnectionInfo.UserID = "userid"
myLogin.ConnectionInfo.Password = "pwd"
myTable.ApplyLogOnInfo(myLogin)
myTable.Location = myTable.Location
CrystalReportViewer1.ReportSource = RptDocument
Created a System DNS and had to add Oracle.DataAccess.dll to reference and a class file (with functions same as that in connectooracle.vb class file but with different name), also set up a connection in global.asax to refer to that class connection and using
Imports Oracle.DataAccess.Client instead of Imports System.Data.OracleClient (to avoid ambiguity)...
This somehow made it work and there might be some other solution for that..:)
(For ref:- Adding myLogin.ConnectionInfo.IntegratedSecurity = True gave me this error--
Logon failed. Error in File C:\DOCUME~1\Username\LOCALS~1\Temp\Report {1AG3DD86-141D-43YA-B6A2-AEDF3459AE49}.rpt: Unable to connect: incorrect log on parameters.)
This works for me and I'm using Visual Studio 2008 for this one since VS2010 doesn't have crystal engine for the reference.
First, make sure you have imported these two:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Now, on my part I was using the odbc because as what I have noticed crystal report works fine with this and since we are working with odbc. So I did not include the login property on the report in my code. On the report just choose odbc connection.
Private Sub ReportViewer_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim cryRpt As New ReportDocument
Dim str1 As String
Try
str1 = Title.str1
str2 =Title.str2
cryRpt.Load("c:\Program Files\Report\" & str2 & "")
Dim crParameterFieldDefinitions As ParameterFieldDefinitions
Dim crParameterFieldDefinition As ParameterFieldDefinition
Dim crParameterValues As New ParameterValues
Dim crParameterDiscreteValue As New ParameterDiscreteValue
crParameterDiscreteValue.Value = strStore
crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
crParameterFieldDefinition = crParameterFieldDefinitions.Item("Store")
crParameterValues = crParameterFieldDefinition.CurrentValues
crParameterValues.Clear()
crParameterValues.Add(crParameterDiscreteValue)
crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)
rptviewer.Cursor = Cursors.AppStarting
rptviewer.ReportSource = cryRpt
rptviewer.Refresh()
rptviewer.Cursor = Cursors.Default
Catch ex As Exception
MsgBox(ex.Message)
Me.Close()
ReportInterface.Show()
End Try
End Sub
I have a class that will get the data inputted by the user. But this will not work using stored procedure parameters.
please mark as accepted if it works for you
Thank You