Click here to Skip to main content
15,867,686 members
Articles / Desktop Programming / Windows Forms

Crystal Report Filtering Using Selection Parameters

Rate me:
Please Sign up or sign in to vote.
4.88/5 (15 votes)
2 Jun 2011CPOL3 min read 262.8K   9.2K   28   29
Beginner's Guide to Crystal Report Filtering

Background

Selection parameters allow you to filter Data returned from datasource (Table in our case).

Of course, it's better and faster to use Stored Procedures (explained here), but it's good to learn about this useful feature.

Step 1: Database

  1. Download and unzip the attached file.
  2. Run the script to create the database and table.
  3. You should now have the following schema.

Schema.jpg

(I tried to use variations of data types, text, datetime, float, etc.)

Step 2: Form

We’ll build the user input form, nothing fancy, textbox, datetimepicker and a customized numeric updown control.

(The numeric updown is augmented to have a Checked property, we’ll need that later.)

Main.jpg

Step 3: Report

Next, we’ll add a new report to our Reports folder, explained here.

Step 4: Report’s Parameters

Very well, we have our report created; next, we want to create the parameters to be passed and searched with.

In addition to the 6 parameters on the user form, we need a Boolean parameter for each field, this Boolean tells us whether to include the field in search criteria or not.

We'll enter the first boolean to indicate if the From datetimepicker has value:

  1. In field explorer,right click Parameter fields>New (if you can't find field explorer, View>Other Windows>Document Outline or Ctrl+Alt+T)

    Parameter_1.jpg

  2. Enter name bHireDateFromChecked and type boolean

    All_params.jpg

  3. Do this for the other fields. bHireDateToChecked bSalaryFromChecked etc…

We don’t need a Boolean to check if user wants to search by name, we’ll just inspect if the text length is greater than zero.

So now we’ve added the Booleans. Next, we’ll add the parameters that will be actually searched.

Similarly add the parameters, with the same datatype they are in database.

So now we have:

SelectDatabase.jpg

Step 5: Report’s Formulas

For each of our Main searchable parameters, we’ll create a formula, this formula examines the parameters attached Boolean, to decide whether to include it in the search or not.

So let’s add a new formula:

  1. Open Field Explorer
  2. Right click Formula Fields>New
  3. Enter name: HireDateFrom

After you click ok,this window appears:

SelectTable.jpg

You have all the parameters you created, if you double click on one of them, it's written into the editor. Great!

So now we’ll write the following formula while clicking parameters of the above panel.

if (double click bHireDateFromChecked) then 
double click t_Employees.dHireDate >= double click dtHireFrom 
Else 
True  

So now you should have the following:

SQL
IF({?bHireDateFromChecked}) THEN
    {t_Employees.dHireDate}>={?dtHireFrom}
ELSE
    TRUE 

Click save and close on the top left.

Similarly, create the formula HireDateTo, which is:

SQL
IF({?bHireDateToChecked})THEN
    {t_Employees.dHireDate}<={?dtHireTo}
ELSE
    TRUE

Similarly create another 2 formulas for salary, from and to.

For the name field, we’ll take a different approach, we’ll check the passed parameter’s length.

(Notice the functions panel in the middle, like the formulas, functions are written into the editor once you double click on one of them.)

Expand Strings in the Functions Panel.

Write:

IF(double click length double click sName)>0)THEN
double click t_Employees.sName = double click sName 
ELSE
TRUE 

And now you should have:

SQL
IF(Length ({?sName})>0)THEN
    {t_Employees.sName}={?sName}
ELSE
    TRUE

Step 6: Selection Parameters

Right click in the empty grey of the report>Report>selection formula>record.

Like the parameters, the formulas we just created are available in the editor.

FieldExplorer.jpg

Now all we have to do is to join these formulas using the logical operator AND.

  1. Double click on each formula to be written in the editor
  2. Write AND between each formula

..and you should end up with this:

SQL
{@HireDateFrom} AND
{@HireDateTo} AND
{@Manager} AND
{@Name} AND
{@SalaryFrom} AND
{@SalaryTo}

Points of Interest

You design the report in one place, then copy it somewhere else.

The report included in the application (the one you see under solution explorer->Reports Folder) is NOT the one the report viewer references to, the actual path is this:

C#
string strReportName = "rptDemo.rpt";
string strPath = Application.StartupPath + "\\Reports\\" + strReportName;

which is the application's bin>Debug WHY?

In a Desktop application, when you want to deploy and add a setup project, this will be the path of the added Report's Folder.

Deploy.jpg

You should NOT hard-code your Connection String.

Almost every CR tutorial I've seen uses hard-coded Connection Strings (they use Datatables too, someone tell me why?)

You should make use of little helpful class called DbConnectionInfo (not mine, unfortunately I can't remember the author to give him credit.)

C#
private void frmReportViewer_Load(object sender, EventArgs e)
        {
            DbConnectionInfo.SetConnectionString(ConfigurationSettings.AppSettings[0]);
            TableLogOnInfo logOnInfo;
            ConnectionInfo connectionInfo;
            foreach (Table table in m_cryRpt.Database.Tables)
            {
                logOnInfo = table.LogOnInfo;
                connectionInfo = logOnInfo.ConnectionInfo;
                // Set the Connection parameters.
                connectionInfo.DatabaseName = DbConnectionInfo.InitialCatalog;
                connectionInfo.ServerName = DbConnectionInfo.ServerName;
                if (!DbConnectionInfo.UseIntegratedSecurity)
                {
                    connectionInfo.Password = DbConnectionInfo.Password;
                    connectionInfo.UserID = DbConnectionInfo.UserName;
                }
                else
                {
                    connectionInfo.IntegratedSecurity = true;
                }
                table.ApplyLogOnInfo(logOnInfo);
            }

            crystalReportViewer1.ReportSource = m_cryRpt;
            crystalReportViewer1.Refresh();
        }

You should let the user know what he entered.

ReportHeader.jpg

Always display the parameters the user entered in a friendly way.

For example, the formula lblHireDateFrom displays the entered From date:

SQL
IF({?bHireDateFromChecked}) THEN
   ToText ({?dtHireFrom})
ELSE
    'Any'

Conclusion

Hope I delivered a clear explanation. Feel free to post any questions/suggestions.

License

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


Written By
Software Developer
Egypt Egypt
Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving, data structures, algorithms, AI, machine learning and nlp.

Amateur guitarist/ keyboardist, squash player.

Comments and Discussions

 
Questionboolean required Pin
Member 1180357230-Jun-15 7:15
Member 1180357230-Jun-15 7:15 
Questionhow do you check the presence of an int value? Pin
Member 109006142-Jul-14 23:19
Member 109006142-Jul-14 23:19 
AnswerRe: how do you check the presence of an int value? Pin
Omar Gameel Salem3-Jul-14 15:33
professionalOmar Gameel Salem3-Jul-14 15:33 
GeneralRe: how do you check the presence of an int value? Pin
Member 109006145-Jul-14 21:57
Member 109006145-Jul-14 21:57 
AnswerRe: how do you check the presence of an int value? Pin
Omar Gameel Salem6-Jul-14 18:40
professionalOmar Gameel Salem6-Jul-14 18:40 
GeneralMy vote of 5 Pin
RookieCoder_NG5-Sep-12 1:20
RookieCoder_NG5-Sep-12 1:20 
GeneralMy vote of 5 Pin
bajwa0135-Jul-12 0:32
bajwa0135-Jul-12 0:32 
QuestionPassing parameter values in crystal reports to stored procedure Pin
Member 886365527-Jun-12 11:58
Member 886365527-Jun-12 11:58 
AnswerRe: Passing parameter values in crystal reports to stored procedure Pin
Omar Gameel Salem27-Jun-12 23:07
professionalOmar Gameel Salem27-Jun-12 23:07 
GeneralRe: Passing parameter values in crystal reports to stored procedure Pin
Member 886365528-Jun-12 5:13
Member 886365528-Jun-12 5:13 
GeneralRe: Passing parameter values in crystal reports to stored procedure Pin
Member 88636551-Jul-12 12:32
Member 88636551-Jul-12 12:32 
GeneralMy vote of 5 Pin
Member 886365527-Jun-12 11:47
Member 886365527-Jun-12 11:47 
QuestionDefault Parameter Panel in Crystal Reports filtering Pin
Member 886365523-Apr-12 8:51
Member 886365523-Apr-12 8:51 
QuestionCrystal Report Filtering Pin
Member 886365523-Apr-12 2:54
Member 886365523-Apr-12 2:54 
AnswerRe: Crystal Report Filtering Pin
Omar Gameel Salem23-Apr-12 3:16
professionalOmar Gameel Salem23-Apr-12 3:16 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey27-Mar-12 23:46
professionalManoj Kumar Choubey27-Mar-12 23:46 
BugLinks broken Pin
Cyrusje23-Jan-12 4:59
Cyrusje23-Jan-12 4:59 
Questionthis is very cool but what about if you want filter from listbox ? Pin
djramc21-Jan-12 2:28
djramc21-Jan-12 2:28 
AnswerRe: this is very cool but what about if you want filter from listbox ? Pin
Omar Gameel Salem21-Jan-12 21:09
professionalOmar Gameel Salem21-Jan-12 21:09 
AnswerRe: this is very cool but what about if you want filter from listbox ? Pin
djramc22-Jan-12 1:37
djramc22-Jan-12 1:37 
GeneralRe: this is very cool but what about if you want filter from listbox ? Pin
Omar Gameel Salem22-Jan-12 1:39
professionalOmar Gameel Salem22-Jan-12 1:39 
GeneralRe: this is very cool but what about if you want filter from listbox ? Pin
djramc22-Jan-12 2:07
djramc22-Jan-12 2:07 
GeneralRe: this is very cool but what about if you want filter from listbox ? Pin
Omar Gameel Salem22-Jan-12 2:08
professionalOmar Gameel Salem22-Jan-12 2:08 
so you removed the if statement and put this only ?
GeneralRe: this is very cool but what about if you want filter from listbox ? Pin
djramc22-Jan-12 2:22
djramc22-Jan-12 2:22 
AnswerRe: this is very cool but what about if you want filter from listbox ? Pin
djramc22-Jan-12 2:12
djramc22-Jan-12 2:12 

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.