I don't know why but this question or slight variants of it,
regularly appear on Stack Overflow. I'm not sure why
because I always found it fairly simple to navigate my way around
the Crystal Reports runtime. I guess a lot of people
don't.
So, enough idle chit chat lets just get on with it shall we?
First we need to set up the Report Object
//Declare an instance of a Crystal Report
ReportDocument _crystalReport = new ReportDocument();
//Set the FileName for the report
_crystalReport.FileName = @"C:\CrystalReports\MyCustomReport.rpt";
Ok, now time for the Parameters
if (parameters.Count > 0)
{
//Add the params here
ParameterValues currentParameterValues = new ParameterValues();
foreach (KeyValuePair<string, string> param in parameters)
{
ParameterDiscreteValue paramDV = new ParameterDiscreteValue();
paramDV.Value = param.Value;
report.ParameterFields[param.Key].CurrentValues.Clear();
report.ParameterFields[param.Key].DefaultValues.Clear();
report.ParameterFields[param.Key].CurrentValues.Add(paramDV);
}
}
You may be wondering what is going on
here, well let me explain.
The parameters object
is of Dictionary<String,String> which I use to store my
parameters in. The key being the parameter name and the value ...
well... being the value. The nice thing about doing it this
way is that you can reuse the same code for any report. Which is
good! But you knew that already.... right?
So, all we do is
- loop through each value in our parameters
Dictionary.
- we then create a new ParameterDiscreteValue object and set its
value.
- we then use the parameters.Key to find the corresponding
Parameter in the Crystal Report.
- then we clear any Current or Default Values that may be stored
in the report
- finally we add our Parameter Discrete Value to the current
parameter
It's that simple! You just need to ensure that the Key value is
exactly the same as the parameter name within the Crystal
Report.
Now for the data source.....
TableLogOnInfo logOnInfo;
foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in report.Database.Tables)
{
logOnInfo= tbCurrent.LogOnInfo;
logOnInfo.ConnectionInfo.DatabaseName = "MyDatabaseName";
logOnInfo.ConnectionInfo.UserID = "UserId";
logOnInfo.ConnectionInfo.Password = "secretpassword";
logOnInfo.ConnectionInfo.ServerName = "SQLServer";
logOnInfo.ConnectionInfo.Type = ConnectionInfoType.SQL;
tbCurrent.ApplyLogOnInfo(logOnInfo);
}
So what are we doing here?
- we declare a TableLogOnInfo object
- then we loop through each Table that exists in the report and
grab the current LogOnInfo.
- we apply our new Data Source details. If you are using
Windows Authentication then you can take out the UserId &
Password.
- We then apply the new data source information to the current
table that we are on.
So thats it - really simple to do and yet the question keeps
popping up all the time.