Click here to Skip to main content
Click here to Skip to main content

Dynamic Crystal Report with C#

By , 29 Sep 2007
 
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.

    /// <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:

    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)

About the Author

Manjula Wickramathunga
Team Leader Creative Technology Solutions Pte Ltd
Sri Lanka Sri Lanka
Member
Manjula Wickramathunga currently is working at Lion Brewery (Ceylon) PLC as a Team Leader. He is working with SAP and Microsoft Technologies such as C#, MS SQL server 2000,2005 and 2008, ASP.NET 2.0/3.5/4.0.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membergorgias9921 Feb '13 - 22:01 
Nice work,
 
I've been using for some years, CR on vs2005 changed at runtime to show or hide columns, change size and font of fields. But instead using parameters, I use formulas.
QuestionNeed a helpmemberriffayu18 Dec '12 - 18:21 
Thanks for this article.
 
In this article you have discussed about adding columns(paramField.Name = "col" + columnNo.ToString()) .
 
My question is i want to know how to add "rows" to the report.
 
In other words, i want to display the search results of 5 different employees(empid is different) from the same table into the same report page.
 
As i am new to sql and crystal report. I dont have any clues about it.
 

Thanks in advance.
BugEnter parameter values crystal reports in c#memberCHAITANYA KIRAN KASANI5 Dec '12 - 21:45 
Hi...I Did The Same Project But For Me "Enter parameter values" Dialog Box Is Showing And Asking For Parameter Values And After I Gave The Values...It Is Showing The Values That I Entered,But Not Showing The Data Retrieving From The Database...Please Help Me..Thanking You
QuestionhimemberNywalikar22 Nov '12 - 0:43 
Thanku Smile | :)
Questionhimemberrifayee17 Oct '12 - 1:32 
hi friend..actually i developing a web application,in that application i placed one gridview control and i displayed all the database values in that gridview...in that gridview i provide an option like print,if i click the print link for the particular record ,the selected record will be displayed in the crystal report.....can u explain me how to do this....
GeneralMy vote of 5memberEaverae20 Sep '12 - 1:27 
great post. keep it up.
GeneralMy vote of 2membermas7775 Jun '12 - 2:17 
in this sample, width of the columns are fixed. this isn't good enough. It'd be better if column width could be dynamically adjusted according to the contents of the column.
GeneralRe: My vote of 2memberEaverae20 Sep '12 - 1:27 
which is not the point of the article.
"My opinion is not represented by my hometown."

GeneralThanks To Authormembersantosh kundkar17 May '12 - 23:03 
Nice and Really Helpful Source Code
Thanks for Code
Big Grin | :-D Big Grin | :-D
QuestionClean data of reportmemberQnhat1 May '12 - 23:55 
Hi,
I have a question about crystal report in visual studio 2008. I use object crystal report viewer for show my report:
 
crystalReportViewer.ReportSource = reportDocument;
crystalReportViewer.ParameterFieldInfo = report.ParameterFields;
crystalReportViewer.Refresh();
 
When I change parameter of report on user interface , memory of program is increase about 3-5 MB. How can I clean old data before change parameter ? I don't know where is data of report. Thanks so much!

Questionabout SQL server..memberDinesh925 Feb '12 - 22:02 
Good afternoon sir,
I m Dinesh..
i m creating a project in ADO.NET with SQL server 2005 as a back end..
i have a question that after deploying my project for installation on OTHER machine..will my program give me error if destination machine server name does not match with my server name which i have used in my application..??
 
i used this code:
 
Data Source=Dinesh; Initial Catalog=college_Management_System; User ID=sa; Password=*****;
 

plz reply me sir soon...Confused | :confused:
 
Dinesh92
GeneralMy vote of 4memberbilawal12118 Jan '12 - 0:43 
it is a good article but i want this same thing that take data from multiple tables,i dont know how to query for this case???
QuestionMy Vote of 5memberroshandavid5 Jan '12 - 5:58 
Well explained
GeneralMy Vote of 5memberRaviRanjankr3 Dec '11 - 3:22 
Nice article Thumbs Up | :thumbsup:
GeneralMy vote of 5memberavcas29 Nov '11 - 5:05 
Thx~~~ Save a lot of time
GeneralMy vote of 5membersantosh kundkar18 Oct '11 - 19:23 
Thanks this is Really working code
QuestionThank you....memberjyothi87.u28 Sep '11 - 4:50 
wonderful demonstration on the subject...
Thank you
GeneralMy vote of 5memberjyothi87.u28 Sep '11 - 4:49 
Really a heartful of thanks ..
very good tutorial...
GeneralDynamic columns without specifying all column names in the reportmemberaswathy.s.888 Jun '11 - 23:19 
Here you have created all columns in the Crystal report and according to the query it is showing up.But without specifying all columns (For more than 20 columns) how to code it?
Questionerror in creating Dynamic Crystal Report with C#memberMember 78825659 May '11 - 22:11 
i am making desktop application using C#.Net and Sql SERVER 2008.I want to make crystal reports after seen your this article i am able to create crystal report...how u wrote in article i did same but when i select the checkbox for report i am getting error "incorrect parameter".i have created a table called Media_Method with fields(Media_method_ID,Media_Name,Target_Audience).Parameter fields after adding crystal report is id,name,target respectively .I have tried follwing code
 
private string CreateSelectQueryAndParameters()
{
ReportDocument reportDocument;
            ParameterFields paramFields;
 
            ParameterField paramField;
            ParameterDiscreteValue paramDiscreteValue;
 
            reportDocument = new ReportDocument();
            paramFields = new ParameterFields();
 
            string query = "SELECT ";
            int columnNo = 0;
 
            if (chbid.Checked)
            {
                columnNo++;
                query = query.Insert(query.Length, "Media_method_ID as Column" +
                columnNo.ToString());
                paramField = new ParameterField();
                paramField.Name = "id" + columnNo.ToString();
                paramDiscreteValue = new ParameterDiscreteValue();
                paramDiscreteValue.Value = "Media method ID";
                paramField.CurrentValues.Add(paramDiscreteValue);
                //Add the paramField to paramFields
                paramFields.Add(paramField);
            }
            if (chbname.Checked)
            {
                columnNo++;
                if (query.Contains("Column"))
                {
                    query = query.Insert(query.Length, ", ");
                }
                query = query.Insert(query.Length, "Media_Name as Column" +
                columnNo.ToString());
 
                paramField = new ParameterField();
                paramField.Name = "col" + columnNo.ToString();
                paramDiscreteValue = new ParameterDiscreteValue();
                paramDiscreteValue.Value = "Media Name";                paramField.CurrentValues.Add(paramDiscreteValue);
                //Add the paramField to paramFields
                paramFields.Add(paramField);
            }
            if (chbtarget.Checked)
            {
                columnNo++; //To determine Column number
                if (query.Contains("Column"))
                {
                    query = query.Insert(query.Length, ", ");
                }
                query = query.Insert(query.Length, "Target_Audience as Column" +
                columnNo.ToString());
 
                paramField = new ParameterField();
                paramField.Name = "col" + columnNo.ToString();             
                paramDiscreteValue = new ParameterDiscreteValue();
                paramDiscreteValue.Value = "Target Audience";
 
                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 Media_Method";
            return query;
        }
 
please check bold content properly
 

 
private void button1_Click(object sender, EventArgs e)
        {
            CrystalReport1 objRpt = new CrystalReport1();
 
            string connString = "Data Source=SW-PC-20;Initial Catalog=PSM;Integrated Security=True";
 
            //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
            {
                SqlConnection Conn = new SqlConnection(connString);
 
                SqlDataAdapter   adepter =
                new SqlDataAdapter(query, connString);
                DataSet1 Ds = new DataSet1();
 
                adepter.Fill(Ds, "Media_Method");
 
                objRpt.SetDataSource(Ds);
                crystalReportViewer1.ReportSource = objRpt;
            }
            catch (SqlException oleEx)
            {
                MessageBox.Show(oleEx.Message);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message);
            }
 
        }
please help me if i am wrong
GeneralMy vote of 4memberHarry HJ Neethling9 May '11 - 2:44 
Its good, but it can do with improvement. Like referencing more than one table.
GeneralProblem with crystal report layout (dynamic)memberintelcore2quad8819 Feb '11 - 20:40 
I posted this my problem in topic : http://www.codeproject.com/Questions/159722/Problem-with-crystal-report-layout-dynamic.aspx
 
Can you help me to resolve it
 
Thanks and Best regards,
GeneralThanksmembermelda_4447 Feb '11 - 3:43 
Thank you! It helps a lot. Smile | :)
GeneralThanksmemberCaptainobvious1 Feb '11 - 22:04 
This has really helped me.
 
I still have the parameter prompt coming up even though the parameters are set.
 
If I disable the prompt I get this error "Unable to get SI_MACHINECHOICE property value".
 
I noticed that the OK button on the parameter prompt submits a postback, do you have some insight on why this is happening?
 
Thanks again
GeneralMy vote of 5memberАslam Iqbal16 Jan '11 - 19:58 
thanks for good works.

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 29 Sep 2007
Article Copyright 2007 by Manjula Wickramathunga
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid