articles

Home / DeveloperSection / Articles / CrystalReportViewer Control in C#.Net

CrystalReportViewer Control in C#.Net

CrystalReportViewer Control in C#.Net

Pushpendra Singh 40910 24-Jan-2011

The CrystalReportViewer Control in C#.Net

The Crystal Report is a Reporting Application that can generate reports from various Data Sources.

How to use CrystalReportViewer Control

Drag and drop CrystalReportViewer control from the toolbox on the window Form.

CrystalReportViewer Control in C#.Net

Steps to create Crystal Report in C#.Net

Step1:

  • Create a Dataset and define the schema by drag and drop the database table from Server Explorer.
  • Right Click Solution Explorer -> Add -> Add New Item -> choose DataSet.
  • Add new Connection in the Server Explorer and expand the connection to retrieve the database tables and choose the required table and drag and drop it in the Dataset xsd pane.

Step2:

  • Create Crystal Report.
  • Right Click Solution Explorer -> Add -> Add New Item -> choose Crystal Report.

Configure the Crystal Report.

STEPS: 

  • Select Report Layout, ProjectData, ADO.NET Datasets
  • Expand ADO.NET Datasets and select the table
  • Select the fields

Code:

Open the Code window of the WebForm and write the following code.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using CrystalDecisions.CrystalReports.Engine;
using System.Windows.Forms;
 
namespace WindowsFormsApplication1
{
    public partial class frmCrystalReportViewer : Form
    {
        public frmCrystalReportViewer()
        {
            InitializeComponent();
        }
  private void frmCrystalReportViewer_Load(object sender, EventArgs e)
        {       
           //Connect to the Database
    string constring = "Server=(local);Database=my;User Id=sa;Password=sa";
            SqlConnection sqlcon = new SqlConnection(constring);
            //Open the connection
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand();
            SqlDataAdapter da = new SqlDataAdapter();
            //Write the query
            cmd.CommandText = "select * from regform";
            da.SelectCommand = cmd;
            cmd.Connection = sqlcon;
            da.SelectCommand = cmd;
            //create a dataset
            DataSet ds = new DataSet();
            da.Fill(ds);
        //Create Crystal report document
            ReportDocument rptdc = new ReportDocument();
     //Set crystal report path
    rptdc.Load("C:\\User\\WindowsFormsApplication1\\CrystalReport1.rpt");
           //Bind dataset to reportdoucument
            rptdc.SetDataSource(ds);
           //Bind ReportSource to crystalReportViewer
           crystalReportViewer1.ReportSource = rptdc;
        }
    }
}

Run the project

Data will bind in the CrystalReportViewer when the application run.

CrystalReportViewer Control in C#.Net


Updated 17-Aug-2020

Leave Comment

Comments

Liked By