Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / C#
Article

Dynamic Crystal Report with C#

Rate me:
Please Sign up or sign in to vote.
4.84/5 (89 votes)
29 Sep 2007CPOL2 min read 547.1K   24.2K   159   92
This program shows how to dynamically load data from a database and application into the Crystal Report
Screenshot - pic2.jpg

Introduction

This program shows how to dynamically load data from a database and application into the Crystal Report. By using this program, we can customize a Crystal Report to some limit at run time of the application like specifying which field (Columns of a particular table) should be displayed in the report.

Background

This problem arose because a group of students from SLIIT asked me how to dynamically generate a Crystal Report using C# 2.0 (.NET 2005). I tried to find a solution for this by searching many forums and sites, but unfortunately I couldn't find any solution for that. Some forums said that there is no way to create dynamic Crystal Reports using .NET 2005. Finally, I found a way to do that.

Using the Code

  1. Create a C# project or add a Form to your existing project.

    Now you can add Checkboxes that correspond to columns of a particular table that should be displayed in the Crystal Report and CrystalReportViewer control to the form.

Screenshot - pic4.jpg

For this demonstration, I have created a database called db1.mdb (in bin\Debug) using Access and created a table called Customer.

  1. Add a DataSet (*.xsd file) to your project using add -> New Items in solution explorer. After that, add a DataTable to the DataSet.

    Screenshot - pic5.jpg

    Add columns to DataTable and name them Column1, Column2, and so on. The number of columns depends on how many columns should be displayed in the Crystal report.

  2. Add a Crystal Report into the project and using the Report Wizard, choose ADO.NET DataSets of the Project data source as the data source of the Crystal Report and select Customer data table of DataSet1 as the selected table of the Crystal Report. Then select fields to be displayed in your report. Then remove Column1…, Column5 objects in Section 2 of the Crystal Report.

    Screenshot - pic7.jpg

    Screenshot - pic8.jpg

  3. Now add parameters called col1, col2col5 (the number of parameters should be equal to the number of columns displayed in the Crystal Report.) using Field Explorer.

    Screenshot - pic9.jpg

  4. Add the following method to your Form for Create SQL SELECT query and assign values to parameters of the Crystal Report according to user selected columns that should be displayed on your report.

    C#
    /// <summary>
    /// This method is used to 
    /// 1. create SELECT query according to the selected column names and 
    /// 2. create parameters and assign values for that parameter
    /// that correspond to the crystal report.
    /// NOTE: This parameter is used to display Column names of the 
    /// Crystal Report according to the user selection.
    /// </summary>
    /// <returns></returns>
    private string CreateSelectQueryAndParameters()
    {
        ReportDocument reportDocument;
        ParameterFields paramFields;
        
        ParameterField paramField;
        ParameterDiscreteValue paramDiscreteValue;
    
        reportDocument = new ReportDocument();
        paramFields = new ParameterFields();
                   
        string query = "SELECT ";
        int columnNo = 0;                
    
        if (chbCode.Checked)
        {
            columnNo++;
            query = query.Insert(query.Length, "Code as Column" +
            columnNo.ToString());
    
            paramField = new ParameterField();
            paramField.Name = "col" + columnNo.ToString();
            paramDiscreteValue = new ParameterDiscreteValue();
            paramDiscreteValue.Value = "Customer Code";
            paramField.CurrentValues.Add(paramDiscreteValue);
            //Add the paramField to paramFields
            paramFields.Add(paramField);
        }
        if (chbFirstName.Checked)
        {
            columnNo++;
            if (query.Contains("Column"))
            {
                query = query.Insert(query.Length, ", ");
            }
            query = query.Insert(query.Length, "FirstName as Column" +
            columnNo.ToString());
            
            paramField = new ParameterField();
            paramField.Name = "col" + columnNo.ToString();
            paramDiscreteValue = new ParameterDiscreteValue();
            paramDiscreteValue.Value = "First Name";
            paramField.CurrentValues.Add(paramDiscreteValue);
            //Add the paramField to paramFields
            paramFields.Add(paramField);
        }
        if (chbLastName.Checked)
        {
            columnNo++; //To determine Column number
            if (query.Contains("Column"))
            {
                query = query.Insert(query.Length, ", ");
            }
            query = query.Insert(query.Length, "LastName as Column" +
            columnNo.ToString());
                            
            paramField = new ParameterField();
            paramField.Name = "col" + columnNo.ToString();
            paramDiscreteValue = new ParameterDiscreteValue();
            paramDiscreteValue.Value = "Last Name";
            paramField.CurrentValues.Add(paramDiscreteValue);
            //Add the paramField to paramFields
            paramFields.Add(paramField);
        }
        if (chbAddress.Checked)
        {
            columnNo++;
            if (query.Contains("Column"))
            {
                query = query.Insert(query.Length, ", ");
            }
            query = query.Insert(query.Length, "Address as Column" +
            columnNo.ToString());
                            
            paramField = new ParameterField();
            paramField.Name = "col" + columnNo.ToString();
            paramDiscreteValue = new ParameterDiscreteValue();
            paramDiscreteValue.Value = "Address";
            paramField.CurrentValues.Add(paramDiscreteValue);
            //Add the paramField to paramFields
            paramFields.Add(paramField);
        }
        if (chbPhone.Checked)
        {
            columnNo++;
            if (query.Contains("Column"))
            {
                query = query.Insert(query.Length, ", ");
            }
            query = query.Insert(query.Length, "Phone as Column" +
            columnNo.ToString());
    
            paramField = new ParameterField();
            paramField.Name = "col" + columnNo.ToString();
            paramDiscreteValue = new ParameterDiscreteValue();
            paramDiscreteValue.Value = "Phone";
            paramField.CurrentValues.Add(paramDiscreteValue);
            //Add the paramField to paramFields
            paramFields.Add(paramField);
        }
    
        //if there is any remaining parameter, assign empty value for that 
        //parameter.
        for (int i = columnNo; i < 5; i++)
        {
            columnNo++;
            paramField = new ParameterField();
            paramField.Name = "col" + columnNo.ToString();
            paramDiscreteValue = new ParameterDiscreteValue();
            paramDiscreteValue.Value = "";
            paramField.CurrentValues.Add(paramDiscreteValue);
            //Add the paramField to paramFields
            paramFields.Add(paramField);
        }
               
        crystalReportViewer1.ParameterFieldInfo = paramFields;
        
        query += " FROM Customer" ;
        return query;
    }
    //
  5. Add the following method to the button click event to display a report when the user presses the button:

    C#
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.OleDb;
    
    using CrystalDecisions.CrystalReports.Engine;
    using CrystalDecisions.ReportSource;
    using CrystalDecisions.Shared;
    using CrystalDecisions.Windows.Forms;
    
    namespace app5
    {
        public partial class Form1 : Form
        {
            CrystalReport1 objRpt;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                objRpt = new CrystalReport1();
    
                string connString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=|DataDirectory|\\db1.mdb"; 
               
                //Get Select query String and add parameters to the 
                //Crystal report.
                string query = CreateSelectQueryAndParameters();
    
                //if there is no item select, then exit from the method.
                if (!query.Contains("Column"))
                {
                    MessageBox.Show("No selection to display!");
                    return;
                }
    
                try
                {
                    OleDbConnection Conn = new OleDbConnection(connString);
    
                    OleDbDataAdapter adepter = 
                    new OleDbDataAdapter(query, connString);
                    DataSet1 Ds = new DataSet1();
    
                    adepter.Fill(Ds, "Customer");
                    
                    objRpt.SetDataSource(Ds);
                    crystalReportViewer1.ReportSource = objRpt;
                }
                catch (OleDbException oleEx)
                {
                    MessageBox.Show(oleEx.Message);
                }
                catch (Exception Ex)
                {
                    MessageBox.Show(Ex.Message);
                }
            }

History

  • 29th September, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
I'm working with SAP and Microsoft Technologies such as C#, MS SQL server, ASP.NET, ASP.NET MVC, WebAPI.

Comments and Discussions

 
GeneralMy vote of 4 Pin
Iakovos Karakizas9-Aug-10 1:38
professionalIakovos Karakizas9-Aug-10 1:38 
GeneralThank you! It helps a lot. Pin
ben197815-May-10 9:09
ben197815-May-10 9:09 
Generalsiraaaaaaaa Pin
amilakandambi11-Apr-10 19:42
amilakandambi11-Apr-10 19:42 
GeneralMy vote of 1 Pin
ssmani84195-Apr-10 19:55
ssmani84195-Apr-10 19:55 
GeneralMy vote of 1 Pin
ssmani84195-Apr-10 19:53
ssmani84195-Apr-10 19:53 
Generaldynamic report in asp.net Pin
niktana16-Mar-10 20:08
niktana16-Mar-10 20:08 
Generalcolumn names not displaying. Pin
rowter12-Jan-10 8:19
rowter12-Jan-10 8:19 
Questionhow to display the column names? Pin
rowter4-Jan-10 18:07
rowter4-Jan-10 18:07 
GeneralSuperb Code Pin
NarendraSinghJTV22-Nov-09 18:27
NarendraSinghJTV22-Nov-09 18:27 
GeneralExcellent code... Pin
pathakmanoj599-Oct-09 1:27
pathakmanoj599-Oct-09 1:27 
Generalnot working Pin
arup200527-Sep-09 18:47
arup200527-Sep-09 18:47 
GeneralYou rock Pin
ChHakim7-Aug-09 18:54
ChHakim7-Aug-09 18:54 
Questioncan i change the width of the column Pin
pnvreddy2-Jul-09 21:17
pnvreddy2-Jul-09 21:17 
Questioncan I set column in center of the report? Pin
m905288884822-May-09 22:01
m905288884822-May-09 22:01 
GeneralThank you very much!! Good article!! Pin
Sangseok Lee7-May-09 5:21
Sangseok Lee7-May-09 5:21 
GeneralThanks for your example Pin
MD844-May-09 16:46
MD844-May-09 16:46 
GeneralPaper Size Pin
newbiecode4-May-09 8:41
newbiecode4-May-09 8:41 
GeneralFinaly Pin
lokalokaloka19-Mar-09 4:52
lokalokaloka19-Mar-09 4:52 
QuestionPrint or export buttong is not working Pin
pulak chetia12-Mar-09 21:27
pulak chetia12-Mar-09 21:27 
GeneralExcellent article Pin
CarlosMPereira5-Mar-09 14:37
CarlosMPereira5-Mar-09 14:37 
GeneralMy vote of 1 Pin
kiddjoe14-Feb-09 16:59
kiddjoe14-Feb-09 16:59 
GeneralVery Good Pin
Member 429754313-Jan-09 20:05
Member 429754313-Jan-09 20:05 
QuestionHow to add charts? Pin
Priya Prk10-Dec-08 7:27
Priya Prk10-Dec-08 7:27 
GeneralParameterDiscreteValue.Description Pin
Death__Inc5-Oct-08 15:27
Death__Inc5-Oct-08 15:27 
Newsdisplying report Pin
shawn41426-Sep-08 13:58
shawn41426-Sep-08 13:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.