Displaying Crystal Reports in a Web Browser
Having tried for a while to find the right information for displaying Crystal Reports properly inside a web page using Crystal Report Viewer I finally managed to pull the information together into a solution that works; well for me anyway.
It’s worth mentioning that I don’t use the Crystal Reports extensions for Visual Studio, I have Crystal Server running on the box. I can’t see how this method wouldn’t work through the Visual Studio extensions.
Code Infront
Register the assembly in the top of your aspx page
<%@ Register TagPrefix="cr" Namespace="CrystalDecisions.Web" Assembly="CrystalDecisions.Web, Version=11.0.3300.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" %>
Place the control where you want it to appear in the page.
<cr:crystalreportviewer id="crReport1" runat="server" hasviewlist="False" hastogglegrouptreebutton="False" hassearchbutton="False" hasgotopagebutton="False" hasdrillupbutton="False" hascrystallogo="False" autodatabind="true" width="350px" displaygrouptree="False" height="50px" hyperlinktarget="_blank">
Code Behind
// declare the variables protected CrystalReportViewer crReport1; private ReportDocument document1 = new ReportDocument(); private TableLogOnInfos infos1 = new TableLogOnInfos(); private TableLogOnInfo info2 = new TableLogOnInfo(); private ConnectionInfo info1 = new ConnectionInfo(); // load the report document1.Load(Request.PhysicalApplicationPath + "myReport.rpt"); // Add the parameters document1.SetParameterValue("param1", "value1"); document1.SetParameterValue("param2", "value2"); //Set the login info for the database info1.ServerName = ConfigurationSettings.AppSettings["server_name"]; info1.DatabaseName = ConfigurationSettings.AppSettings["database_name"]; info1.UserID = ConfigurationSettings.AppSettings["user_id"]; info1.Password = ConfigurationSettings.AppSettings["password"]; Tables tables1 = document1.Database.Tables; //Apply login info to the report foreach (CrystalDecisions.CrystalReports.Engine.Table table1 in tables1) { info2 = table1.LogOnInfo; info2.ConnectionInfo = info1; table1.ApplyLogOnInfo(info2); } // Bind the report crReport1.ReportSource = document1; crReport1.DataBind();
You also need to remember to close the document after it has been rendered to free up memory. This should ideally be done in the Page_Unload method. See this post on MSDN for more information on why it should be placed in Page_Unload.
Posted in Web Development