Thursday, February 7, 2013

Crystal Reports in ASP.NET







Crystal Reports in Visual Studio 2010

First download and install CRforVS_13_0_4  ,from sap site  ,that is the crystalreport engine for vs2010.


Create an ASP.NET Empty website.

Then we will create a DataSet. For this, right click on the project name in Solution Explorer and click Add New Item. The Add New Item Dialog will open. Select DataSet from the list of items. Give it's name as per your choice  and click Add.
Now we will add the table to the DataSet. On the Server Explorer right click Data Connections and then click Add Connection.






Enter your server name and select the Database.


After that drag a table to the DataSet designer and save it.

Now right click on the project in Solution Explorer and select Add New Item. Select Crystal Report from the list and add it as CustomerReport.

The Crystal Report Gallery will open. Select Blank Report and click OK.


Now in the field explorer window right click on Database Fields and click Database Expert.

Click the plus sign of Project Data, then ADO.NET DataSets. Select Customers under Customer. Click the add (>) button to add the table to our report and click OK.





You will get all the fields of the Customers table under the Customers option under Database Fields in Field Explorer. Drag and drop the required fields in the Section 3 (Details) part of the report and save it.




Finally drag CrystalReportViewer control from the Reporting section of the Toolbox to our webpage. 


Now go to the code behind page and write the following code in the Page_Load event.



using System.Data;
using System.Data.SqlClient;
using CrystalDecisions.CrystalReports.Engine;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection("Server=myserver;uid=sa;pwd=nothing;Database=MyDB;");

        SqlCommand command = new SqlCommand("Select top 10 * From Customers", connection);

        SqlDataAdapter adapter = new SqlDataAdapter(command);

        //Customer _Customer = new Customer();
        DataSet dataset = new DataSet();

        adapter.Fill(dataset, "Customer");

        ReportDocument CustomerReport = new ReportDocument();

        CustomerReport.Load(Server.MapPath("CustomerReport.rpt"));

        CustomerReport.SetDataSource(dataset.Tables["Customer"]);

        CrystalReportViewer1.ReportSource = CustomerReport;

        CrystalReportViewer1.DataBind();
    }
}





0 comments:

Post a Comment