How to pass in Report Parameters into SSRS Report Viewer if parameters do not exist in the report?

Viewed 29

The follow code passes ReportParameters into SSRS report viewer to generate a report.

ReportParameter[] reportParameter = new ReportParameter[2];
reportParameter[0] = new ReportParameter("Parameter1", Parameter1);
reportParameter[1] = new ReportParameter("Parameter2", Parameter2);
ReportViewer1.ServerReport.SetParameters(reportParameter);
ReportViewer1.ServerReport.Refresh();

The following is a sample report with one of the parameters missing. I set the parameter "Parameter1" in this report. enter image description here

Is there a way to programmatically make the C# code set the parameter to "none" if parameter is missing in the report and still generate the report?

As of now, the code will attempt to push the value for "Parameter2" into the report but since that parameter has not been set in the report, the report will not generate.

2 Answers

Try setting a parameter only after verified if it exists in report.

VB.NET code with LocalReport but you can easily translate it in C# / ServerReport:

Dim listReportParameters As New List(Of ReportParameter)

For Each rptParameter As ReportParameter In {New ReportParameter("ReportParameter1", "PARAMETER_1"), New ReportParameter("ReportParameter2", "PARAMETER_2")}
    For Each infoReportParameter As ReportParameterInfo In ReportViewer1.LocalReport.GetParameters
        If infoReportParameter.Name = rptParameter.Name Then
            listReportParameters.Add(rptParameter)
            Exit For
        End If
    Next infoReportParameter
Next rptParameter

Me.ReportViewer1.LocalReport.SetParameters(listReportParameters)

The solution was to use the GetParameter() to check for the existing parameters in the report and then generate the list of parameters using some conditional statements, and then setting those parameters with SetPrameters().

var currentParametersInTheReport = ReportViewer1.ServerReport.GetParameters();

List<ReportParameter> systemReportParameter = new List<ReportParameter>();
if (currentParametersInTheReport.Any(r => r.Name == "Parameter1"))
{
    systemReportParameter.Add(new ReportParameter("Parameter1", Parameter1));
}
if (currentParametersInTheReport.Any(r => r.Name == "Parameter2"))
{
    systemReportParameter.Add(new ReportParameter("Parameter2", Parameter2));
}

ReportViewer1.ServerReport.SetParameters(systemReportParameter);
ReportViewer1.ServerReport.Refresh();

This approach will check for the parameters first, then build the list of parameters to send to the ReportViewer component, and then send those parameters to generate the report.

Related