Post date: Nov 14, 2009 12:17:52 AM
This sample code below is used to generate the crystal report dynamically using asp.net (C#). This code has been tried and tested and works fine.
Assuming your crystal report will have the data from Stored Procedure. Now add the crystal report into your project using the wizard.
Now go to your aspx page (design mode) and add the CrystalReportViewer from the Toolbox (see file Add_CR_aspx_page.png).
The code snippet is as below:
ReportDocument crystalReport = new ReportDocument();
Reports rp = new Reports();
DataSet ds = rp.GetDate();
DataTable dt = new DataTable();
dt = ds.Tables[0];
crystalReport.Load(Server.MapPath("~\\rptFiles\\MyCrystalReport.rpt"));
crystalReport.SetParameterValue("@FromDate", ReportFromDateTextBox.Text);
crystalReport.SetParameterValue("@ToDate", ReportToDatev.Text);
crystalReport.SetDataSource(dt);
CrystalReportViewer1.ReportSource = crystalReport;
crystalReport.Refresh();
Session[SessionKeys.MyReport1] = crystalReport; //Or Viewstate
The above code is placed in the Button click event which will get the data from the Database and stores in dataset. If you assign dataset as datasource to reportcocument, it will not work and will throw an error. Hence we are assigning datatable as datasource.
If you need to print the report or navigate to different pages of the report, it will not work and shows blank pages (shows only 1st and 2nd page). In order to navigate to all the pages or print all the pages, you need to bind the report in init as shown below.
I have used session to hold the report data but you can also use viewstate or any other mechanism.
protected void Page_Init(object sender, EventArgs e)
{
if (Session[SessionKeys.repArrivalListName] != null)
{
CrystalReportViewer1.ReportSource = (ReportDocument)Session[SessionKeys.MyReport1];
}
}