将参数从 Web 表单传递到 Crystal 报表

发布于 2024-10-29 12:28:49 字数 1008 浏览 0 评论 0原文

我有一份报告,我想将其显示在网络表单上。没有参数的报告运行良好。带参数的报告让我很头疼。这是我在 BindReport 方法中编写的代码,该代码在表单的页面加载事件上调用。

    ReportDocument rpt = new ReportDocument();
    rpt.Load(Server.MapPath("rptPositionwiseMontwiseActualSale.rpt"));
    rpt.FileName = Server.MapPath("rptPositionwiseMontwiseActualSale.rpt");
    rpt.SetParameterValue("CompanyName", "Cirin Pharmaceutical Pvt. Limited".ToString());
    rpt.SetParameterValue("ReportTitle", "PositionWise MonthWise Sales".ToString());
    rpt.SetParameterValue("parameters", "Year:2011".ToString());
    //CrystalReportViewer1.ParameterFieldInfo = paramFields;
    DataSet ds = getReportData();
    rpt.SetDataSource(ds.Tables[0]);
    CrystalReportViewer1.ReportSource = rpt;
    CrystalReportViewer1.ReuseParameterValuesOnRefresh = true;
   
    //CrystalReportViewer1.RefreshReport();

我尝试了各种方法,例如将 ParameterFieldInfo 分配给报表查看器控件,但它在页面加载时显示提示,要求提供报表的参数值。我正在使用.NET 4.0。

编辑

我正在使用 Crystal Reports 的推送模型。它是否改变了我们从 asp.net 传递参数以进行报告的方式?

I have a report and I want to display it on a webform. Reports without parameters are working well. Reports with parameters are creating headache for me. This is the code I have written in BindReport method, which is called on page load event of the form.

    ReportDocument rpt = new ReportDocument();
    rpt.Load(Server.MapPath("rptPositionwiseMontwiseActualSale.rpt"));
    rpt.FileName = Server.MapPath("rptPositionwiseMontwiseActualSale.rpt");
    rpt.SetParameterValue("CompanyName", "Cirin Pharmaceutical Pvt. Limited".ToString());
    rpt.SetParameterValue("ReportTitle", "PositionWise MonthWise Sales".ToString());
    rpt.SetParameterValue("parameters", "Year:2011".ToString());
    //CrystalReportViewer1.ParameterFieldInfo = paramFields;
    DataSet ds = getReportData();
    rpt.SetDataSource(ds.Tables[0]);
    CrystalReportViewer1.ReportSource = rpt;
    CrystalReportViewer1.ReuseParameterValuesOnRefresh = true;
   
    //CrystalReportViewer1.RefreshReport();

I have tried variety of things like assigning ParameterFieldInfo to reportviewer control, but it shows me prompt on page load asking for parameter values of the report. I'm using .NET 4.0.

Edit

I'm using push model for Crystal Reports. Does it change the way we can pass parameters to report from asp.net?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一身仙ぐ女味 2024-11-05 12:28:49

在运行时为 ASP.NET 设置参数值时,我认为您需要做更多的工作,而不仅仅是调用 SetParameterValue

string rptTitle = "This is Report Title";

rpt.SetParameterValue("ReportTitle", rptTitle);

ParameterDiscreteValue val = new ParameterDiscreteValue();
val.Value = rptTitle;

ParameterValues paramVals = new ParameterValues();

paramVals.Add(val);

rpt.ParameterFields["ReportTitle"].CurrentValues = paramVals;

rpt.DataDefinition.ParameterFields[0].ApplyCurrentValues(paramVals);

这可能有点矫枉过正,但它确实有效,无论如何对我来说都很好。您必须确保参数名称完全匹配。

When setting Parameter values at runtime for ASP.NET I think you need to do a bit more work than just called SetParameterValue

string rptTitle = "This is Report Title";

rpt.SetParameterValue("ReportTitle", rptTitle);

ParameterDiscreteValue val = new ParameterDiscreteValue();
val.Value = rptTitle;

ParameterValues paramVals = new ParameterValues();

paramVals.Add(val);

rpt.ParameterFields["ReportTitle"].CurrentValues = paramVals;

rpt.DataDefinition.ParameterFields[0].ApplyCurrentValues(paramVals);

This is probably a bit of overkill but it does actually work, well for me anyway. You must ensure that the parameter names match exactly.

情话墙 2024-11-05 12:28:49

这是我在项目中使用的代码来查看水晶报告(它是一个Web控件)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Objects.Controls;
using System.Data.SqlClient;
using Objects.Database;
using System.IO;
using System.Configuration;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;

namespace App.WebControls
{
    /// <summary>
    /// Crystal Report Viewer Control
    /// </summary>
    public partial class CrystalReportViewer : BaseWebControl
    {
        //- MEMBER VARIABLES --------------------------------------------------------------------------------------------------------

        #region Members

        private CrystalDecisions.Shared.ParameterFields m_ParameterFields = new CrystalDecisions.Shared.ParameterFields();
        private CrystalDecisions.Web.CrystalReportSource m_CrystalReportSource = new CrystalDecisions.Web.CrystalReportSource();

        #endregion Members

        //- PROPERTIES --------------------------------------------------------------------------------------------------------------

        #region Properties

        /// <summary>
        /// Gets or Sets the Crystal Report Source
        /// </summary>
        public CrystalDecisions.Web.CrystalReportSource ReportSource
        {
            get { return m_CrystalReportSource; }
            set { m_CrystalReportSource = value; }
        }

        /// <summary>
        /// Gets the Name of the WAP data source name
        /// </summary>
        public string WAPDataSourceName
        {
            get
            {
                if ( ViewState[ "WAPDataSourceName" ] == null )
                {
                    ViewState[ "WAPDataSourceName" ] = "WAP";
                }

                return ViewState[ "WAPDataSourceName" ] as string;
            }
            set
            {
                ViewState[ "WAPDataSourceName" ] = value;
            }
        }

        /// <summary>
        /// Gets the Name of the Sage Datasource Name
        /// </summary>
        public string SageDataSourceName
        {
            get
            {
                if ( ViewState[ "SageDataSourceName" ] == null )
                {
                    ViewState[ "SageDataSourceName" ] = "WAP_Sage";
                }

                return ViewState[ "SageDataSourceName" ] as string;
            }
            set
            {
                ViewState[ "SageDataSourceName" ] = value;
            }
        }

        /// <summary>
        /// Gets or Sets the Report Filename
        /// </summary>
        public string ReportFileName
        {
            get
            {
                return ReportSource.Report.FileName;
            }
            set
            {
                ReportSource.Report.FileName = value;
            }
        }

        /// <summary>
        /// Gets or Sets the Sage Database
        /// </summary>
        public SageDatabase SageDatabase
        {
            get
            {
                if ( ViewState[ "SageDatabase" ] == null )
                {
                    ViewState[ "SageDatabase" ] = new SageDatabase();
                }

                return ViewState[ "SageDatabase" ] as SageDatabase;
            }
            set
            {
                ViewState[ "SageDatabase" ] = value;
            }
        }

        /// <summary>
        /// Gets the Current Paramter Fields
        /// </summary>
        public CrystalDecisions.Shared.ParameterFields ParameterFields
        {
            get
            {
                return m_ParameterFields;
            }
        }

        #endregion Properties

        //- EVENTS ------------------------------------------------------------------------------------------------------------------

        #region Events

        /// <summary>
        /// Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load( object sender, EventArgs e )
        {
            try
            {
                if ( !this.IsPostBack )
                {
                    //Set up the Report Source
                    this.SetReportSource();

                    //Set the Connections
                    this.ConfigureReports();

                    //Sets the Parameters
                    this.SetParameters();
                }
            }
            catch ( Exception )
            {
                throw;
            }
        }

        #endregion Events

        //- METHODS -----------------------------------------------------------------------------------------------------------------

        #region Methods

        /// <summary>
        /// Gets a connection info object based on a SQL connection string
        /// </summary>
        /// <param name="oSqlConnectionStringBuilder">The connection string builder</param>
        /// <param name="ServerName">The server name the connection is for</param>
        /// <returns>Connection Info</returns>
        private ConnectionInfo GetConnectionInfo( SqlConnectionStringBuilder oSqlConnectionStringBuilder, string ServerName )
        {
            try
            {
                ConnectionInfo oConnectionInfo = new ConnectionInfo();

                oConnectionInfo.ServerName = ServerName;
                oConnectionInfo.DatabaseName = oSqlConnectionStringBuilder.InitialCatalog;
                oConnectionInfo.UserID = oSqlConnectionStringBuilder.UserID;
                oConnectionInfo.Password = oSqlConnectionStringBuilder.Password;
                oConnectionInfo.IntegratedSecurity = oSqlConnectionStringBuilder.IntegratedSecurity;
                oConnectionInfo.Type = ConnectionInfoType.SQL;
                oConnectionInfo.AllowCustomConnection = true;

                return oConnectionInfo;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Sets the DB logon info for the report
        /// </summary>
        /// <param name="oConnectionInfo">The connection info to set</param>
        private void SetDBLogonForReport( ConnectionInfo oConnectionInfo )
        {
            try
            {
                TableLogOnInfos oTableLogOnInfos = ReportViewer.LogOnInfo;

                foreach ( CrystalDecisions.CrystalReports.Engine.Table oTable in ReportSource.ReportDocument.Database.Tables )
                {
                    if ( oTable.LogOnInfo.ConnectionInfo.ServerName == oConnectionInfo.ServerName )
                    {
                        TableLogOnInfo oTableLogOnInfo = oTable.LogOnInfo;

                        oTableLogOnInfo.ConnectionInfo = oConnectionInfo;

                        oTable.ApplyLogOnInfo( oTableLogOnInfo );

                       // oTable.Location = String.Format( "{0}.dbo.{1}", oConnectionInfo.DatabaseName, oTable.Name );

                        bool b = oTable.TestConnectivity();

                        if ( !b )
                        {
                        }
                    }
                }

            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Configures the reports
        /// </summary>
        private void ConfigureReports()
        {
            try
            {
                //Get connection infos
                ConnectionInfo sageConnectionInfo = this.GetConnectionInfo( new SqlConnectionStringBuilder( this.SageDatabase.ConnectString ), this.SageDataSourceName );
                ConnectionInfo wapConnectionInfo = this.GetConnectionInfo( new SqlConnectionStringBuilder( ConfigurationManager.ConnectionStrings[ "DatabaseConnectString" ].ConnectionString ), this.WAPDataSourceName );

                //Set db logon for the connection infos
                this.SetDBLogonForReport( sageConnectionInfo );
                this.SetDBLogonForReport( wapConnectionInfo );
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Adds a discrete parameteer value
        /// </summary>
        /// <param name="ParameterName">The namee of the parameter to set</param>
        /// <param name="value">The value of the parameter</param>
        public void AddDiscreteValue( string ParameterName, object value )
        {
            try
            {
                //Create a new Parameter Field
                CrystalDecisions.Shared.ParameterField oParameterField = new CrystalDecisions.Shared.ParameterField();
                oParameterField.Name = ParameterName;

                //Create a new Discrete Value
                CrystalDecisions.Shared.ParameterDiscreteValue oParameterDiscreteValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
                oParameterDiscreteValue.Value = value;

                //Add the value
                oParameterField.CurrentValues.Add( oParameterDiscreteValue );

                //Add the parameter field
                this.ParameterFields.Add( oParameterField );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Sets up the Report Source
        /// </summary>
        private void SetReportSource()
        {
            try
            {
                //Load the report based on Filename
                this.ReportSource.ReportDocument.Load( Server.MapPath( this.ReportFileName ) );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Exports the report to disk
        /// </summary>
        /// <param name="FileName">The name of the file</param>
        public void ExportToDisk( string FileName )
        {
            try
            {
                this.ReportSource.ReportDocument.ExportToDisk( CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, FileName );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Exports the Report to Email 
        /// </summary>
        [Obsolete( "Bug in Crystal Reports objects that causes the attachment to be called untitled.txt", true )]
        public void ExportToMAPI()
        {
            try
            {
                CrystalDecisions.Shared.ExportOptions oExportOptions = new CrystalDecisions.Shared.ExportOptions();
                {
                    CrystalDecisions.Shared.MicrosoftMailDestinationOptions oMicrosoftMailDestinationOptions = new CrystalDecisions.Shared.MicrosoftMailDestinationOptions();
                    oMicrosoftMailDestinationOptions.MailToList = "[email protected]";
                    oMicrosoftMailDestinationOptions.MailSubject = "test";
                    oMicrosoftMailDestinationOptions.MailMessage = "Body text";

                    CrystalDecisions.Shared.PdfRtfWordFormatOptions oPdfRtfWordFormatOptions = new CrystalDecisions.Shared.PdfRtfWordFormatOptions();


                    oExportOptions.ExportDestinationOptions = oMicrosoftMailDestinationOptions;
                    oExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.MicrosoftMail;
                    oExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
                    oExportOptions.ExportFormatOptions = oPdfRtfWordFormatOptions;

                    this.ReportSource.ReportDocument.Export( oExportOptions );
                }
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Exports the Current Report to a Stream
        /// </summary>
        /// <returns></returns>
        public Stream ExportToStream()
        {
            try
            {
                return this.ReportSource.ReportDocument.ExportToStream( CrystalDecisions.Shared.ExportFormatType.PortableDocFormat );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Sets the Parameters
        /// </summary>
        private void SetParameters()
        {
            try
            {
                if ( this.ParameterFields.Count > 0 )
                {
                    //Set the Parameters
                    this.ReportViewer.ParameterFieldInfo = this.ParameterFields;
                }

                //Set the report source
                this.ReportViewer.ReportSource = this.ReportSource;
            }
            catch ( Exception )
            {
                throw;
            }
        }

        #endregion Methods

        //---------------------------------------------------------------------------------------------------------------------------
    }
}

要在代码中使用它:

/// <summary>
/// Page Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load( object sender, EventArgs e )
{
    try
    {
        if ( !Page.IsPostBack )
        {
            //Set the report filename
            this.CrystalReportViewer.ReportFileName = @"~/Reports/WAP Std Sage PurchaseOrder.rpt";

            if ( base.CurrentOrder != null )
            {
                //Set the Sage Database
                this.CrystalReportViewer.SageDatabase = base.CurrentOrder.SageDatabase;

                //Set Order ID parameter
                this.CrystalReportViewer.AddDiscreteValue( "OrderID", base.CurrentOrder.OrderID );

            }
        }
    }
    catch ( Exception ex )
    {
        ErrorLogging.LogError( ex );
    }
}

主要要查看的方法是用户控件中的AddDiscreteValue和SetParameters

编辑:

抽象的相关方法:

/// <summary>
            /// Sets the Parameters
            /// </summary>
            private void SetParameters()
            {
                try
                {
                    if ( this.ParameterFields.Count > 0 )
                    {
                        //Set the Parameters
                        this.ReportViewer.ParameterFieldInfo = this.ParameterFields;
                    }

                    //Set the report source
                    this.ReportViewer.ReportSource = this.ReportSource;
                }
                catch ( Exception )
                {
                    throw;
                }
            }

/// Adds a discrete parameteer value
            /// </summary>
            /// <param name="ParameterName">The namee of the parameter to set</param>
            /// <param name="value">The value of the parameter</param>
            public void AddDiscreteValue( string ParameterName, object value )
            {
                try
                {
                    //Create a new Parameter Field
                    CrystalDecisions.Shared.ParameterField oParameterField = new CrystalDecisions.Shared.ParameterField();
                    oParameterField.Name = ParameterName;

                    //Create a new Discrete Value
                    CrystalDecisions.Shared.ParameterDiscreteValue oParameterDiscreteValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
                    oParameterDiscreteValue.Value = value;

                    //Add the value
                    oParameterField.CurrentValues.Add( oParameterDiscreteValue );

                    //Add the parameter field
                    this.ParameterFields.Add( oParameterField );
                }
                catch ( Exception )
                {
                    throw;
                }
            }

Here is the code Im using in a project to view crystal reports (its a web control)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Objects.Controls;
using System.Data.SqlClient;
using Objects.Database;
using System.IO;
using System.Configuration;
using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;

namespace App.WebControls
{
    /// <summary>
    /// Crystal Report Viewer Control
    /// </summary>
    public partial class CrystalReportViewer : BaseWebControl
    {
        //- MEMBER VARIABLES --------------------------------------------------------------------------------------------------------

        #region Members

        private CrystalDecisions.Shared.ParameterFields m_ParameterFields = new CrystalDecisions.Shared.ParameterFields();
        private CrystalDecisions.Web.CrystalReportSource m_CrystalReportSource = new CrystalDecisions.Web.CrystalReportSource();

        #endregion Members

        //- PROPERTIES --------------------------------------------------------------------------------------------------------------

        #region Properties

        /// <summary>
        /// Gets or Sets the Crystal Report Source
        /// </summary>
        public CrystalDecisions.Web.CrystalReportSource ReportSource
        {
            get { return m_CrystalReportSource; }
            set { m_CrystalReportSource = value; }
        }

        /// <summary>
        /// Gets the Name of the WAP data source name
        /// </summary>
        public string WAPDataSourceName
        {
            get
            {
                if ( ViewState[ "WAPDataSourceName" ] == null )
                {
                    ViewState[ "WAPDataSourceName" ] = "WAP";
                }

                return ViewState[ "WAPDataSourceName" ] as string;
            }
            set
            {
                ViewState[ "WAPDataSourceName" ] = value;
            }
        }

        /// <summary>
        /// Gets the Name of the Sage Datasource Name
        /// </summary>
        public string SageDataSourceName
        {
            get
            {
                if ( ViewState[ "SageDataSourceName" ] == null )
                {
                    ViewState[ "SageDataSourceName" ] = "WAP_Sage";
                }

                return ViewState[ "SageDataSourceName" ] as string;
            }
            set
            {
                ViewState[ "SageDataSourceName" ] = value;
            }
        }

        /// <summary>
        /// Gets or Sets the Report Filename
        /// </summary>
        public string ReportFileName
        {
            get
            {
                return ReportSource.Report.FileName;
            }
            set
            {
                ReportSource.Report.FileName = value;
            }
        }

        /// <summary>
        /// Gets or Sets the Sage Database
        /// </summary>
        public SageDatabase SageDatabase
        {
            get
            {
                if ( ViewState[ "SageDatabase" ] == null )
                {
                    ViewState[ "SageDatabase" ] = new SageDatabase();
                }

                return ViewState[ "SageDatabase" ] as SageDatabase;
            }
            set
            {
                ViewState[ "SageDatabase" ] = value;
            }
        }

        /// <summary>
        /// Gets the Current Paramter Fields
        /// </summary>
        public CrystalDecisions.Shared.ParameterFields ParameterFields
        {
            get
            {
                return m_ParameterFields;
            }
        }

        #endregion Properties

        //- EVENTS ------------------------------------------------------------------------------------------------------------------

        #region Events

        /// <summary>
        /// Page Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load( object sender, EventArgs e )
        {
            try
            {
                if ( !this.IsPostBack )
                {
                    //Set up the Report Source
                    this.SetReportSource();

                    //Set the Connections
                    this.ConfigureReports();

                    //Sets the Parameters
                    this.SetParameters();
                }
            }
            catch ( Exception )
            {
                throw;
            }
        }

        #endregion Events

        //- METHODS -----------------------------------------------------------------------------------------------------------------

        #region Methods

        /// <summary>
        /// Gets a connection info object based on a SQL connection string
        /// </summary>
        /// <param name="oSqlConnectionStringBuilder">The connection string builder</param>
        /// <param name="ServerName">The server name the connection is for</param>
        /// <returns>Connection Info</returns>
        private ConnectionInfo GetConnectionInfo( SqlConnectionStringBuilder oSqlConnectionStringBuilder, string ServerName )
        {
            try
            {
                ConnectionInfo oConnectionInfo = new ConnectionInfo();

                oConnectionInfo.ServerName = ServerName;
                oConnectionInfo.DatabaseName = oSqlConnectionStringBuilder.InitialCatalog;
                oConnectionInfo.UserID = oSqlConnectionStringBuilder.UserID;
                oConnectionInfo.Password = oSqlConnectionStringBuilder.Password;
                oConnectionInfo.IntegratedSecurity = oSqlConnectionStringBuilder.IntegratedSecurity;
                oConnectionInfo.Type = ConnectionInfoType.SQL;
                oConnectionInfo.AllowCustomConnection = true;

                return oConnectionInfo;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Sets the DB logon info for the report
        /// </summary>
        /// <param name="oConnectionInfo">The connection info to set</param>
        private void SetDBLogonForReport( ConnectionInfo oConnectionInfo )
        {
            try
            {
                TableLogOnInfos oTableLogOnInfos = ReportViewer.LogOnInfo;

                foreach ( CrystalDecisions.CrystalReports.Engine.Table oTable in ReportSource.ReportDocument.Database.Tables )
                {
                    if ( oTable.LogOnInfo.ConnectionInfo.ServerName == oConnectionInfo.ServerName )
                    {
                        TableLogOnInfo oTableLogOnInfo = oTable.LogOnInfo;

                        oTableLogOnInfo.ConnectionInfo = oConnectionInfo;

                        oTable.ApplyLogOnInfo( oTableLogOnInfo );

                       // oTable.Location = String.Format( "{0}.dbo.{1}", oConnectionInfo.DatabaseName, oTable.Name );

                        bool b = oTable.TestConnectivity();

                        if ( !b )
                        {
                        }
                    }
                }

            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Configures the reports
        /// </summary>
        private void ConfigureReports()
        {
            try
            {
                //Get connection infos
                ConnectionInfo sageConnectionInfo = this.GetConnectionInfo( new SqlConnectionStringBuilder( this.SageDatabase.ConnectString ), this.SageDataSourceName );
                ConnectionInfo wapConnectionInfo = this.GetConnectionInfo( new SqlConnectionStringBuilder( ConfigurationManager.ConnectionStrings[ "DatabaseConnectString" ].ConnectionString ), this.WAPDataSourceName );

                //Set db logon for the connection infos
                this.SetDBLogonForReport( sageConnectionInfo );
                this.SetDBLogonForReport( wapConnectionInfo );
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// Adds a discrete parameteer value
        /// </summary>
        /// <param name="ParameterName">The namee of the parameter to set</param>
        /// <param name="value">The value of the parameter</param>
        public void AddDiscreteValue( string ParameterName, object value )
        {
            try
            {
                //Create a new Parameter Field
                CrystalDecisions.Shared.ParameterField oParameterField = new CrystalDecisions.Shared.ParameterField();
                oParameterField.Name = ParameterName;

                //Create a new Discrete Value
                CrystalDecisions.Shared.ParameterDiscreteValue oParameterDiscreteValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
                oParameterDiscreteValue.Value = value;

                //Add the value
                oParameterField.CurrentValues.Add( oParameterDiscreteValue );

                //Add the parameter field
                this.ParameterFields.Add( oParameterField );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Sets up the Report Source
        /// </summary>
        private void SetReportSource()
        {
            try
            {
                //Load the report based on Filename
                this.ReportSource.ReportDocument.Load( Server.MapPath( this.ReportFileName ) );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Exports the report to disk
        /// </summary>
        /// <param name="FileName">The name of the file</param>
        public void ExportToDisk( string FileName )
        {
            try
            {
                this.ReportSource.ReportDocument.ExportToDisk( CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, FileName );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Exports the Report to Email 
        /// </summary>
        [Obsolete( "Bug in Crystal Reports objects that causes the attachment to be called untitled.txt", true )]
        public void ExportToMAPI()
        {
            try
            {
                CrystalDecisions.Shared.ExportOptions oExportOptions = new CrystalDecisions.Shared.ExportOptions();
                {
                    CrystalDecisions.Shared.MicrosoftMailDestinationOptions oMicrosoftMailDestinationOptions = new CrystalDecisions.Shared.MicrosoftMailDestinationOptions();
                    oMicrosoftMailDestinationOptions.MailToList = "[email protected]";
                    oMicrosoftMailDestinationOptions.MailSubject = "test";
                    oMicrosoftMailDestinationOptions.MailMessage = "Body text";

                    CrystalDecisions.Shared.PdfRtfWordFormatOptions oPdfRtfWordFormatOptions = new CrystalDecisions.Shared.PdfRtfWordFormatOptions();


                    oExportOptions.ExportDestinationOptions = oMicrosoftMailDestinationOptions;
                    oExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.MicrosoftMail;
                    oExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
                    oExportOptions.ExportFormatOptions = oPdfRtfWordFormatOptions;

                    this.ReportSource.ReportDocument.Export( oExportOptions );
                }
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Exports the Current Report to a Stream
        /// </summary>
        /// <returns></returns>
        public Stream ExportToStream()
        {
            try
            {
                return this.ReportSource.ReportDocument.ExportToStream( CrystalDecisions.Shared.ExportFormatType.PortableDocFormat );
            }
            catch ( Exception )
            {
                throw;
            }
        }

        /// <summary>
        /// Sets the Parameters
        /// </summary>
        private void SetParameters()
        {
            try
            {
                if ( this.ParameterFields.Count > 0 )
                {
                    //Set the Parameters
                    this.ReportViewer.ParameterFieldInfo = this.ParameterFields;
                }

                //Set the report source
                this.ReportViewer.ReportSource = this.ReportSource;
            }
            catch ( Exception )
            {
                throw;
            }
        }

        #endregion Methods

        //---------------------------------------------------------------------------------------------------------------------------
    }
}

To use this in code:

/// <summary>
/// Page Load
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load( object sender, EventArgs e )
{
    try
    {
        if ( !Page.IsPostBack )
        {
            //Set the report filename
            this.CrystalReportViewer.ReportFileName = @"~/Reports/WAP Std Sage PurchaseOrder.rpt";

            if ( base.CurrentOrder != null )
            {
                //Set the Sage Database
                this.CrystalReportViewer.SageDatabase = base.CurrentOrder.SageDatabase;

                //Set Order ID parameter
                this.CrystalReportViewer.AddDiscreteValue( "OrderID", base.CurrentOrder.OrderID );

            }
        }
    }
    catch ( Exception ex )
    {
        ErrorLogging.LogError( ex );
    }
}

The main methods to look at are AddDiscreteValue and SetParameters in the User Control

EDIT:

Abstracted relevant methods:

/// <summary>
            /// Sets the Parameters
            /// </summary>
            private void SetParameters()
            {
                try
                {
                    if ( this.ParameterFields.Count > 0 )
                    {
                        //Set the Parameters
                        this.ReportViewer.ParameterFieldInfo = this.ParameterFields;
                    }

                    //Set the report source
                    this.ReportViewer.ReportSource = this.ReportSource;
                }
                catch ( Exception )
                {
                    throw;
                }
            }

/// Adds a discrete parameteer value
            /// </summary>
            /// <param name="ParameterName">The namee of the parameter to set</param>
            /// <param name="value">The value of the parameter</param>
            public void AddDiscreteValue( string ParameterName, object value )
            {
                try
                {
                    //Create a new Parameter Field
                    CrystalDecisions.Shared.ParameterField oParameterField = new CrystalDecisions.Shared.ParameterField();
                    oParameterField.Name = ParameterName;

                    //Create a new Discrete Value
                    CrystalDecisions.Shared.ParameterDiscreteValue oParameterDiscreteValue = new CrystalDecisions.Shared.ParameterDiscreteValue();
                    oParameterDiscreteValue.Value = value;

                    //Add the value
                    oParameterField.CurrentValues.Add( oParameterDiscreteValue );

                    //Add the parameter field
                    this.ParameterFields.Add( oParameterField );
                }
                catch ( Exception )
                {
                    throw;
                }
            }
挽清梦 2024-11-05 12:28:49

就这样用吧。

    SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["MainDB"].ConnectionString);
    SqlCommand cmd = new SqlCommand();

    #region Help Method
    private void ProjectDataBind()
    {
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        try
        {
            Con.Open();
            cmd.CommandText = "sp_Project_SelectAll";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Connection = Con;

            adapter.Fill(ds, "tbl_Project");
          }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cmd.Dispose();
            if (Con.State != ConnectionState.Closed)
                Con.Close();
        }
        //DataTable dt = controller.SelectAll();
        cboFromProject.DataTextField = "Project";
        cboFromProject.DataValueField = "ProjectID";
        cboFromProject.DataSource = ds.Tables[0];
        cboFromProject.DataBind();

    }
    private void ToProjectDataBind()
    {
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        try
        {
            Con.Open();
            cmd.CommandText = "sp_Project_SelectAll";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Connection = Con;

            adapter.Fill(ds, "tbl_Project");
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cmd.Dispose();
            if (Con.State != ConnectionState.Closed)
                Con.Close();
        }
        //DataTable dtable = controller.SelectAll();
        cboToProject.DataTextField = "Project";
        cboToProject.DataValueField = "ProjectID";
        cboToProject.DataSource = ds.Tables[0];//dtable;
        cboToProject.DataBind();
    }
    public DataSet getFromTOProjects(int fproject, int toproject)
    {

        //string sqlCon = ConfigurationManager.AppSettings["MainDB"].ToString();

        DataSet ds = null;
        SqlDataAdapter adapter;
        try
        {
            Con.Open();
            cmd.CommandText = "sp_projectReport_ByProject";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@fproject", fproject));
            cmd.Parameters.Add(new SqlParameter("@toproject", toproject));
            cmd.Connection = Con;
            ds = new DataSet();
            adapter = new SqlDataAdapter(cmd);
            adapter.Fill(ds, "tbl_Project");
            //adapter.Fill(ds);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cmd.Dispose();
            if (Con.State != ConnectionState.Closed)
                Con.Close();
        }
        return ds;
    }
    #endregion


   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ProjectDataBind();
            ToProjectDataBind();
        }
        if (IsPostBack)
        {
            try
            {
                CrystalReportViewer2.ReportSource = (ReportDocument)Session["Report"];
                //CrystalReportViewer2.RefreshReport(); write this code,will prompt
                //CrystalReportViewer2.DataBind();
            }
            catch (Exception ex)
            {

                // throw;
            }
        }

    }
    protected void btnPreview_Click(object sender, EventArgs e)
    {

            ReportDocument rptDoc = new ReportDocument();
            DataSet ds = new DataSet();
            DataTable dtable = new DataTable();
            dtable.TableName = "tbl_Project";
            ds = getFromTOProjects(Convert.ToInt32(cboFromProject.SelectedValue), Convert.ToInt32(cboToProject.SelectedValue));
            dtable = ds.Tables[0];

            rptDoc.Load(Server.MapPath("~\\Reports\\ProjectReportWithPara.rpt"));
            rptDoc.SetDataSource(dtable);
            rptDoc.SetParameterValue("ReportTitle", "Project Report By Project");
            rptDoc.SetParameterValue("FromProject", cboFromProject.SelectedItem.Text);
            rptDoc.SetParameterValue("ToProject", cboToProject.SelectedItem.Text);

            //string rptTitle = "This is Report Title";

            //rpt.SetParameterValue("ReportTitle", rptTitle);

            //ParameterDiscreteValue val = new ParameterDiscreteValue();
            //val.Value = rptTitle;

            //ParameterValues paramVals = new ParameterValues();

            //paramVals.Add(val);

            //rpt.ParameterFields["ReportTitle"].CurrentValues = paramVals;

            //rpt.DataDefinition.ParameterFields[0].ApplyCurrentValues(paramVals);

            Session["Report"] = rptDoc;
            CrystalReportViewer2.ReportSource = rptDoc;

            //CrystalReportViewer2.ReuseParameterValuesOnRefresh = false; 
            //CrystalReportViewer2.DataBind();
            //CrystalReportViewer2.ReportSource = rptDoc.Clone(); 
     // can print and export but prompt already set parameters
            //CrystalReportViewer2.RefreshReport();

    }

Use like that.

    SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["MainDB"].ConnectionString);
    SqlCommand cmd = new SqlCommand();

    #region Help Method
    private void ProjectDataBind()
    {
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        try
        {
            Con.Open();
            cmd.CommandText = "sp_Project_SelectAll";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Connection = Con;

            adapter.Fill(ds, "tbl_Project");
          }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cmd.Dispose();
            if (Con.State != ConnectionState.Closed)
                Con.Close();
        }
        //DataTable dt = controller.SelectAll();
        cboFromProject.DataTextField = "Project";
        cboFromProject.DataValueField = "ProjectID";
        cboFromProject.DataSource = ds.Tables[0];
        cboFromProject.DataBind();

    }
    private void ToProjectDataBind()
    {
        DataSet ds = new DataSet();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        try
        {
            Con.Open();
            cmd.CommandText = "sp_Project_SelectAll";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Connection = Con;

            adapter.Fill(ds, "tbl_Project");
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cmd.Dispose();
            if (Con.State != ConnectionState.Closed)
                Con.Close();
        }
        //DataTable dtable = controller.SelectAll();
        cboToProject.DataTextField = "Project";
        cboToProject.DataValueField = "ProjectID";
        cboToProject.DataSource = ds.Tables[0];//dtable;
        cboToProject.DataBind();
    }
    public DataSet getFromTOProjects(int fproject, int toproject)
    {

        //string sqlCon = ConfigurationManager.AppSettings["MainDB"].ToString();

        DataSet ds = null;
        SqlDataAdapter adapter;
        try
        {
            Con.Open();
            cmd.CommandText = "sp_projectReport_ByProject";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@fproject", fproject));
            cmd.Parameters.Add(new SqlParameter("@toproject", toproject));
            cmd.Connection = Con;
            ds = new DataSet();
            adapter = new SqlDataAdapter(cmd);
            adapter.Fill(ds, "tbl_Project");
            //adapter.Fill(ds);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
            cmd.Dispose();
            if (Con.State != ConnectionState.Closed)
                Con.Close();
        }
        return ds;
    }
    #endregion


   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ProjectDataBind();
            ToProjectDataBind();
        }
        if (IsPostBack)
        {
            try
            {
                CrystalReportViewer2.ReportSource = (ReportDocument)Session["Report"];
                //CrystalReportViewer2.RefreshReport(); write this code,will prompt
                //CrystalReportViewer2.DataBind();
            }
            catch (Exception ex)
            {

                // throw;
            }
        }

    }
    protected void btnPreview_Click(object sender, EventArgs e)
    {

            ReportDocument rptDoc = new ReportDocument();
            DataSet ds = new DataSet();
            DataTable dtable = new DataTable();
            dtable.TableName = "tbl_Project";
            ds = getFromTOProjects(Convert.ToInt32(cboFromProject.SelectedValue), Convert.ToInt32(cboToProject.SelectedValue));
            dtable = ds.Tables[0];

            rptDoc.Load(Server.MapPath("~\\Reports\\ProjectReportWithPara.rpt"));
            rptDoc.SetDataSource(dtable);
            rptDoc.SetParameterValue("ReportTitle", "Project Report By Project");
            rptDoc.SetParameterValue("FromProject", cboFromProject.SelectedItem.Text);
            rptDoc.SetParameterValue("ToProject", cboToProject.SelectedItem.Text);

            //string rptTitle = "This is Report Title";

            //rpt.SetParameterValue("ReportTitle", rptTitle);

            //ParameterDiscreteValue val = new ParameterDiscreteValue();
            //val.Value = rptTitle;

            //ParameterValues paramVals = new ParameterValues();

            //paramVals.Add(val);

            //rpt.ParameterFields["ReportTitle"].CurrentValues = paramVals;

            //rpt.DataDefinition.ParameterFields[0].ApplyCurrentValues(paramVals);

            Session["Report"] = rptDoc;
            CrystalReportViewer2.ReportSource = rptDoc;

            //CrystalReportViewer2.ReuseParameterValuesOnRefresh = false; 
            //CrystalReportViewer2.DataBind();
            //CrystalReportViewer2.ReportSource = rptDoc.Clone(); 
     // can print and export but prompt already set parameters
            //CrystalReportViewer2.RefreshReport();

    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文