Wednesday, 7 December 2011

Basic JQuery Interview Questions


What is jQuery & its significance? Why it is so popular?
jQuery is lightweight, client side script JavaScript library file that supports all browsers.Query is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery makes it easy to play with the DOM, add effects, and execute Ajax requests.
This helps developer to reduce lines of code while he program. For example huge code written in Java Script, can be done easily with JQuery in one or two lines as it uses pre compiled JavaScript library internally. For example To find a Div that have class xxx we can do this using custom JavaScript by looping through all DOM elements, Find Div element write if statement checking the class then write the code to manipulate cross browser.  But this can be achieved using jQuery with 2 lines of code. jQuery is a fun library to use and play.
It is so popular due to the below 10 reasons.
  • Cross Browser Compatibility.
  • Fast but micro Famework.The jQuery core library minified is only about 24KB in size, so it is very easily to include in any application and it is pretty fast as well.
  • Easy to learn and flexible.
  • It is well documented.
  • Reuse of plug-ins across projects .These plug ins are extendable.
  • Latest CSS Complaint.
  • Microsoft, which now includes jQuery with its MVC framework and integrated to VS2010 with intellisense support .
  • IBM, Netflix use jQuery. Nokia have adopted it. Google uses and hosts the jQuery library.
  • Easy to find support since there is a large development community and variety of plug-ins.
  • DOM manipulation with querying and chaining is Wonderful & Robust. It is simple, concise and clear enough.
Hence jQuery is definitely faster, easier and more productive than previous traditional JavaScript that we use, hence its so popular.
Now the Client side development is fun using jQuery Agree or not ??
What are jQuery Class Selectors and ID selectors Explain them?
jQuery selectors  allows to easily identify set of page elements for performing user friendly or required operations .
In general, Selection of elements  can be 3 types in jQuery. They are
1.  Class Selector (.)
2.  ID Selector (#)
3.  Element selector (<element tag>)
We will learn Class and ID selectors in this article and will learn about element selectors in the next article.
Class Selector (.)
A class selector is to identify class to search for. An element can have multiple classes. There is no restriction.  Operations are applied based on the class that matches.
$(.demo) – Selects all elements in side a web page with the class demo
Example of using class Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div class="beyondrelational"> This is Div  using class selector </div>
08.<p class="beyondrelational"> This is P using class selector </p>
09. 
10.<script>$(".beyondrelational").css("border","8px solid blue");</script> 
11.</body>
12. 
13.</html>
ID Selector (#)
An element can be selected or indentified based on id.  It Matches a single element with the given id attribute.
$('#EmpNo)  - Selects an element with the ID EmpNo in the web page.
Example of using ID Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div id="beyondrelational"> This is Div class using ID selector </div>  
08.<script>$("#beyondrelational").css("border","8px solid blue");</script> 
09.</body>
10.</html>
Selecting class and ID Selectors at a time (Multiple selectors)
1.$("#IDSel, .ClassSel")
The above selector syntax selects all elements with id IDSel and the class ClassSel.
We can also select elements in webform directly using jQuery , that we will discuss in next post. Till then keep visiting !!!
What is the significance of jQuery.NoConflict?
If we are referring any other script files along with jQuery you may get conflicts in the namespace. Some times if we use jQuery with any other libraries, we may get clash between two libraries and we encounter situations like neither of the functionality works.
Important thing to keep in mind is , when we call .noConflict() jQuery will return $() to it’s previous owner .So we  need to use jQuery() instead of  $() function.
The following example illustrated how to use no conflict . This can be used in cases “where one script works with out the other and will not work when both the scripts are combined”.
01.<html>
02.<head>
03.<script src="xxx.js"></script>
04.<script src="jquery.js"></script>
05.<script>
06.jQuery.noConflict();
07. 
08.// Use jQuery via jQuery(...)
09.jQuery(document).ready(function(){
10.jQuery("div").hide();
11.});
12. 
13.//can Use Prototype with $(...), etc.
14.$('id').hide();
15.</script>
16.</head>
17.<body></body>
18.</html>
The jQuery library and all  plugins are within the jQuery namespace. But "global" objects are stored inside the jQuery namespace . so It is usual to get namespace clash  between jQuery and any other library or plug-in. $ is just short cut for jQuery. Hence overriding $ function will work.
You can also assign in another variable and use it in the application like this as shown below.
01.<html>
02.<head>
03.<script src="xxx.js"></script>
04.<script src="jquery.js"></script>
05.<script>
06.var $j = jQuery.noConflict();
07. 
08.// Use jQuery via $j(...)
09.$j(document).ready(function(){
10.$j("div").hide();
11.});
12. 
13.// Use Prototype with $(...), etc.
14.$('someid').hide();
15.</script>
16.</head>
17.<body></body>
18.</html>
Working with jQuery Selectors – Events .
How to get All I tags inside an element with id ‘header’ ?
Now  we understood what is ID selector, class selector and to select elements, putting all together we will try to answer the above question
For ex: $('#header >I')  - Gets get All I tags inside an element with id ‘header’ .

ID Selector with on Click Event
1.$('#header >I') .Click(function()
2.{   //Open
3.alert(this.innerHTML);
4.});  // Close
Here we are firing click event means that, the mouse click event fires the function. And the corresponding operations in the event are fired. In this case a simple alert message.
 Class Selector with Mouse Over Event
1.$('.content').mouseover(function()
2.{
3.this.innerHTML = 'Content Replaced';
4.});
The above code snippet select all the elements that has class ‘content’,Mouse over of the element content/ text associated with element will be replace
Here Methods can be applied to sequence of objects.
How can you select various HTML Elements using jQuery?
jQuery can be used to select HTML elements using element selector. Below are some of the examples of how to use selectors.
  • $(<’element>’)  - Selects all elements with the given tag name.
  • $(‘p’) – Selects all  Paragraph  Elements
  • $(‘a’) – Selects all Anchor tags in side a web page
  • $(‘I’)  - Selects all Italic tags in the webpage
  • $(‘input[type=text]’) – Selects all textboxes in side a webpage
After selection we can call methods .
Selecting multiple elements
$(‘p,a,div,span’) – Selects all p, a, div, span elements in the web page.
<script>$("p").after( $("b") );</script>
The above script selects all p and makes the content after <p> tag as bold. 
Selecting all the elements
$(‘*’) – This will select all html elements in web form 
Example
<html>
<head><script src="http://code.jquery.com/jquery-latest.js"></script> </head>
<body>
<input type='text' />
<textarea > </textarea>
</body>
<script>
$('input[type=text], textarea').css({width: '70%'});
</script>
</html>
What are jQuery Class Selectors and ID selectors Explain them?
jQuery selectors  allows to easily identify set of page elements for performing user friendly or required operations .
In general, Selection of elements  can be 3 types in jQuery. They are
1.  Class Selector (.)
2.  ID Selector (#)
3.  Element selector (<element tag>)
We will learn Class and ID selectors in this article and will learn about element selectors in the next article.
Class Selector (.)
A class selector is to identify class to search for. An element can have multiple classes. There is no restriction.  Operations are applied based on the class that matches.
$(.demo) – Selects all elements in side a web page with the class demo
Example of using class Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div class="beyondrelational"> This is Div  using class selector </div>
08.<p class="beyondrelational"> This is P using class selector </p>
09. 
10.<script>$(".beyondrelational").css("border","8px solid blue");</script> 
11.</body>
12. 
13.</html>
ID Selector (#)
An element can be selected or indentified based on id.  It Matches a single element with the given id attribute.
$('#EmpNo)  - Selects an element with the ID EmpNo in the web page.
Example of using ID Selector
01.<html>
02.<head>
03.<script src="http://code.jquery.com/jquery-latest.js"></script>
04.</head>
05. 
06.<body>
07.<div id="beyondrelational"> This is Div class using ID selector </div>  
08.<script>$("#beyondrelational").css("border","8px solid blue");</script> 
09.</body>
10.</html>
Selecting class and ID Selectors at a time (Multiple selectors)
1.$("#IDSel, .ClassSel")
The above selector syntax selects all elements with id IDSel and the class ClassSel.
We can also select elements in webform directly using jQuery , that we will discuss in next post. Till then keep visiting !!!
What are jQuery Selectors? Explain them?
A Selector identifies an HTML element tag that is used to manipulate with jQuery code.
Selectors allow page elements to be selected. $ is the symbol used for it.
$ can also be called as jQuery selector. Selectors are the most important part of the jQuery , we can say that heart of jQuery.
  • We can select single (using id selectors) or multiple elements using class or element selectors
  • Selectors find DOM Elements to manipulate based on CSS Selector syntax
    Selectors can find the elements by ID, class, Element Name and hierarchical positioning .
  • Selectors can return sequence of DOM elements , and we can use methods or logic on every matched element.
Selectors syntax can be in either of  following 2 ways :
$(Selector Expression)
or
jQuery(Selector Expression)
jQuery has different types of selectors
1. Class Selectors
2. ID Selectors
3. Element Selectors
What is difference between jQuery and Microsoft Ajax? When do you use Ajax and When do you use jQuery? What is the significance of each?
jQuery is like the ASP.NET AJAX Client Framework (MicrosoftAjax.js), with selectors, DOM selections/ manipulations, plug-ins, and better animation support.  jQuery is more powerful than MS AJAX on the client side due to its light weight nature .  This is the reason Microsoft integrated jQuery with Visual Studio. JQuery is integrated for post  VS versions 2008, no explicit download of jQuery file is required for the versions above VS2010.  
Ajax is a Technology for Asynchronous Data Transferring. AJAX is a technique to do an XMLHttpRequest  from a web page to the server and send or receive data to be used on the web page.
jQuery can be used
If you love and comfortable with JavaScript
Most interaction is client-side only
If a custom solution is required
For stunning look and feel of client side UI
If animations ,DOM Selection are required
Ajax can be used
If you are using ASP.NET & VS
When server side Integration is required.
If you need json and WCF Support
Conclusion
  • jQuery and Ajax often used in conjunction with each other for better results.
  • jQuery is  used to modify data on the webpage dynamically and it  can use AJAX to retrieve data that needs without changing the current state of the displayed page through partial post backs
·         Playing with CSS in jQuery – How to work with CSS in jQuery?
·         How can we apply css to elements using JQuery library.
·         The below example is to apply css on div element that has id as DivId.
·         1.$(”#DivId “).css(”border”,”4px  red”);
·         To apply css in odd childs of parent node using JQuery library.
·         1.$(”tr:odd”).css(”background-color”, “#bbbbff”);
·         To apply css in even childs of parent node using JQuery library.
·         1.$(”tr:even”).css(”background-color”, “#bbbbff”);
·         To apply css in last child of parent using JQuery library.
·         1.$(”tr:last”).css({backgroundColor: ‘yellow’, fontWeight: ‘bolder’});
·         Now How can we modify css class using JQuery library?
·         Suppose that Css class has following definition
·         1..class
·         2.{
·         3.font-size:10px;
·         4.font-weight:normal;
·         5.color:#000000;
·         6.}
·         Now  if we are intrested to  add border property on above class, so we should follow below code.
·         1.$(“.class”).css(“border”,”1px solid blue”);
·         Where $(“.class”) name of css class. Now .class will automatically add border property in his class definition.
Happy jQuerying !!!!
What is $.disconnect significance and how it is different from $.disconnectAll
In jQuery to disconnect one function from another function then $.disconnect is used. Once this statement gets executed, function gets disconnected from reference function and the connected function will not be executed after the code.
Syntax is same as connect function. To disconnect c2.fun1 use the following code
1.$.disconnect(a,'fun1',b,fun2);
Where fun1 is the reference function and fun2 is connected function. Here a, b are objects.
$.disconnectAll function is used to disconnect all connected functions.
1.$.disconnectAll(a,'fun1');

What is jQuery Connect ? How to use jQuery Connect?
This is a jQuery plugin that is used to connect / bind a function to another function. It is more of assigning a handler for another function. Connect is used to execute a function whenever a function from another object or plugin is executed. We can connect to an event of a DOM element too using this function. In the sense same connect function can be used for both DOM elements and for the functions.
1.$.connect(refobj,refFuncName, connObj,connFunc);
This means that, when the reference function is executed, the connected function gets executed automatically after it. To understand more please analyze the following example
01.function A(){
02.this.fun1 = function(){
03.called1 = 'calssA-fun1';
04.}
05.}
06.var a = new A();
07.function B(){
08.this.fun2 = function(){
09.called2 = 'classB-fun1';
10.}
11.}
12.var b = new B();
13.$.connect(a,'fun1',b,fun2);
Here we connected "fun2" of object b to "fun1" of object a. When we call b.fun2, a.fun1 will also execute automatically.
This is very handy to execute some function when some other function is executed from the plug-in . In order to play with it follow these steps.
  • Download jquery.connect.js file.
  • Include this file in your html file.
  • Take help of $.connect function as illustrated to connect a function to another function.
In what scenarios jQuery can be used?
  • To apply CSS static or dynamic
  • To call functions on events
  • Crisscross the documents
  • Manipulation purpose
  • To add animation effects
In all the cases we are using JavaScript can be replaced with jQuery in the projects. This can reduce maintenance.

Do you prefer jQuery or JavaScript? Explain Why?
jQuery solves major JavaScript problems.
jQuery is preferred over JavaScript due to following reasons.
jQuery is light weight library for developing client side applications including ajax.
jQuery assists to keep code simple and concise and reusable. Huge line of code developed using JavaScript can be eliminated with just few lines of jQuery.
jQuery library simplifies the process of traversal of HTML DOM tree.
jQuery can also handle events, perform animation, and add Ajax support in web applications.
Creating animation and effects using JavaScript is not an easy task and requires deep understanding and imagination. This is quite difficult to do using JavaScript.
When a client wants  to zoom entire screen, or to show a slideshow of photographs, this can be achieved using jQuery.  With a few script includes and smart work , its  possible and extremely effective.  Using  variety of jquery Plugging that are available customization is easy for developers , web developers have control over the effects without even touching a single line of raw Javascript.  Thats the power of query.
If you know the JavaScript well, it helps you to make better use of jQuery.
To distinguish jQuery from JavaScript Here is an example for basic animation using javascript .
01.var example = null; // object
02.function doMove() {
03.example.style.left = parseInt(example.style.left)+1+'px';
04.setTimeout(doMove,20); // call doMove in 20msec
05.}
06.function init() {
07.example = document.getElementById('example'); // get the "example" object
08.example.style.left = '0px'; // set its initial position to 0px
09.doMove(); // start animating
10.}
11.window.onload = init;
Now if we we wanted to customize the animation or add wavy or some other different animation its quite difficult using JavaScript. But using jQuey its easy to customize using Plug-ins available. The same animation can be achieved using jQuery as
1.$("#element").animate({ left: 200px; });
JavaScirpt is a Sea and jQuery is a Ship . Together allow us to sail if used effectively. We should only know when to use what!!!

What are the advantages of jQuery?
  1. Easy and Self Explanatory
  2. JavaScript enhancement without headache of learning new syntax.
  3. The code is simple, clear, readable, reusable and also easy to maintainable.
  4. Elimination of writing repeated, complex loops and DOM scripting library calls.
Explain how jQuery works?
The $() function is an alias for the jQuery() function . This returns a special Java-Script object. This JavaScript Object contains an array of  DOM elements that matches the selector. Selector is key thing in jQuery development.It is away to select node from DOM. This Java-Script object possesses a large number of useful predefined methods that can action group of elements.This type of construct is termed a wrapper because it wraps the matching element(s) with extended functionality.
  • Here $(object) is called jQuery wrapper around the object.
  • jQuery has a ready element that checks the document and waits until document is ready to be manipulated.
  • It searches for the reference files for framework, once it finds it then control goes to the function specified.
  • What ever code mentioned in the function that gets executed. Event handling also can be implemented here.
Consider the following example.
01.<html>
02.<head>
03.<script type="text/javascript" src="jquery.js"></script>
04.<script type="text/javascript">
05.$(document).ready(function(){
06.// Your code here
07.alert(“Checking function Fired”);
08. 
09.}
10.) ;
11.</script>
12.</head>
13.<body>
14.<a href="http://www.beyondrelational.com /">Beyond Relational jQuery FAQ </a>
15.</body>
16.</html>
1.<strong><em>Note :We can also use jQuery(document) instead of $. </em></strong>
  • You can debug the jquery script by placing debugger keyword (OR) attaching worker process and then inserting a break point .
How did you use jQuery in ASP.Net Application? Explain with an example?
·         Download the latest jQuery library from jQuery.com http://docs.jquery.com/Downloading_jQuery.
·         Add reference to the jQuery library file in ASPX page / Master page that uses jQuery.
·         1.<script src="_scripts/jQuery-1.5.js" type="text/javascript"></script>
·         2.<script language="javascript">
·         3.$(document).ready(function(){ $("a").click(function(event)
·         4.{ alert("Welcome to jQuery"); }); });
·         5.</script>

Does document.ready() function similar to onload()? (or) Explain the importance of document.ready()? (or) Why jQuery script is faster?
Document.ready() function is completely different from body onload() function .
Explanation
JavaScript Operations on the page elements are performed outside of the DOcument Markup (DOM) that creates them. This is because of waiting until  DOM elements of the page are fully loaded before those operations execute. The onload handler for the window object is used for this purpose, executing statements after the entire page is fully loaded.
Browser delays calling onload till DOM tree is created and then  all images/other external resources are fully loaded.
jQuery waits until DOM tree is ready before executing scripts. jQuery uses this approach using Document.Ready . This makes running scripts fast. jQuery triggers execution of code once the DOM tree is loaded , but not external image resources has loaded.  Hence script execution need not wait till the page is loaded. The code execution happens before page is loaded hence jQuery code is faster. We can use this technique multiple times within the same HTML document.
To summarize the differences
  • First of all Document.ready() function is called as soon as DOM is loaded but body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.
  • We can have as many document.ready() functions in a page but onload function is limited on one time.
What do Dollar ($) sign significance in jQuery?
Dollar Sign is nonetheless an alias for JQuery. You can write jQuery syntax using $ sign or jQuery.
This can also be called Selector($).
This can be called as an expression for identifying target elements on a page that allows  to easily identify and also  grab elements required.
The below 2 syntaxes are the same to create a function using jQuery.
To collect a group of elements, we use the simple syntax $(selector) or jQuery(selector).
1.$(document).ready(function()
2.{
3. 
4.});
OR
1.jQuery(document).ready(function()
2.{
3. 
4.});
Example for a Hyperlink Click
1.$("a").click(function() {});

What are the various jQuery features?

The following are important features of jQuery.
Extensibility
The jQuery Framework is easily extensible. 
DOM elements manipulations
It easily handles DOM element selections functions, manipulations, traversal and modification.
Event Handling
We can implement Event Handling at client side.
CSS manipulation
It provides the flexibility for CSS manipulation. We can apply or change CSS dynamically using jQuery.
Animations
Advanced effects and animations are possible using jQuery.
Cross Browser Compatibility
It is Consistent across all browsers.
Easy Plugins
Number of plug-in or widgets available to achieve certain functionality like paging, sorting, drag , accordion etc.
What is jQuery UI?
jQuery UI  is a library which is built on top of JQuery library.  It can be called as one of the JavaScript plug-in that allows to create animations, sortables list, draggle list . This is developed as separate JavaScript File. This can be downloaded from http://ui.jquery.com/download (ui.jQuery.js).
jQuery UI  responsible for widgets,  components , themes , advanced effects , animation  and interaction mechanism that is UI related things.
Accordions, sliders, dialog boxes, date pickers, and more. All these are ready to be used right now.
jQuery UI  can be used to build highly interactive web applications.
You need to include latest jQuery , UI Core and Flora theme style sheet to work with jQuery UI.
In addition to the above source files you may need to refer each of the component files like ui.draggable.js, ui.resizable.js, ui.accordian.js etc .
or  you may will have to refer jquery.ui.all.js script that contains all component .js files . But do not refer all if you are not using . It is advised to refer only the required files. You can also build the custom download .js file by selecting the required widgets .
This is used for Resizing (resizable method is plugged in jQuery UI), Exploding or animations.
The following is an example code that uses  jQuery UI.
Refer the script files.
1.<link rel="stylesheet" href="themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)" />
2.<script src="http://code.jquery.com/jquery-latest.js"></script>
3.<script src="ui/ui.core.js"></script>
Refer the required Components
1.<script src="ui/ui.draggable.js"></script>
2.<script src="ui/ui.resizable.js"></script>
3.<script src="ui/ui.accordion.js"></script>
1.$(document).ready(function() {
2.$("#dragme").draggable();
3.$("#dragme-x").draggable({ axis: "x" });
4.$("#accordionDemo").accordion({ event: "mouseover" });
5.$("#dragme-resize").draggable().resizable();
6.})
jQuery UI future is hope to be expecting excited and positive.


Original source and author = Hema
http://beyondrelational.com/blogs/hima/archive/2011/10/01/basic-jquery-interview-questions.aspx

Thursday, 1 December 2011

C# Crystal Reports Export to Excel

There are situations when we want to export Crystal reports to .xls format programmatically in C#. In these situations we can use ExportOptions for export the Crystal Reports to .xls format. Also we have to set ExcelFormatOptions and ExportFormatType.Excel . In the following example you can see how to export a Crystal Reports as a Excel format file.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
In this section we are using our earlier program step by step tutorial for creating a Crystal Reports from C# for pull data from database to Crystal Reports . Before we start this section take a look at the step by step tutorial for creating a Crystal Reports from C# .
Here we are generating a Crystal Report from Product table and export the report content to an Excel format file.
Select the default form (Form1.cs) you created in C# and drag two buttons (Button1, Button2 ) and a CrystalReportViewer control to your form.
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;



using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        ReportDocument cryRpt;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cryRpt = new ReportDocument();
            cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
            crystalReportViewer1.ReportSource = cryRpt;
            crystalReportViewer1.Refresh(); 
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                ExportOptions CrExportOptions ;
                  
                DiskFileDestinationOptions CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                ExcelFormatOptions CrFormatTypeOptions = new ExcelFormatOptions();
                CrDiskFileDestinationOptions.DiskFileName = "c:\\csharp.net-informations.xls";
                CrExportOptions = cryRpt.ExportOptions;
                CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
                CrExportOptions.ExportFormatType = ExportFormatType.Excel;
                CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                CrExportOptions.FormatOptions = CrFormatTypeOptions;
                cryRpt.Export();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
The Crystal Reports file path in your project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal Reports file like c:\projects\crystalreports\CrystalReport1.rpt

When you run this program you will get the Excel file (csharp.net-informations.xls) in your computer's C:
 

C# Crystal Reports - Date to Date

The following program describes how to generate a Date to Date report from Crystal Reports in C#
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
In the previous sections explains How to pass C# Crystal Reports Date Paramater and also explain C# Dynamic logon parameters in Crystal Reports. So before we start this section take a look at the previous sections because we are here using sections from these tutorial.
Hope you understand the previous two sections well (1 - C# Crystal Reports Date Paramater, 2 - C# Dynamic logon parameters in Crystal Reports). Here we are creating two date parameter and pass it to Crystal Report at run time also the Crystal Report using dynamic logon parameter to access database.
Createting two date parameters (dateFrom and dateTo).
Date From parameter.
csharp-crystal-reports-datefrom
Date To Parameter
csharp-crystal-reports-dateto
Here we have three tables selected for report (ordermaster , orderdetails and product ) and we are making the formula like , select all records from the tables whose order date is between fromDate parameter and toDate paramater . For doing this you have to select from date as Ordermaster.orderdate, to date as Ordermaster.orderdate , comparison operators , boolean operator (AND) and date parameters fromdate and todate fields from selection list of Formula Editor and make the formula.
The following picture shows how to select the fields from formula editor and make the formula. Double click each field then it will automatically selected .
csharp-crystal-reports-datetodate-formula
After the creation of selection formula you can close that screen .
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in CSharp and drag two Textboxs (from date entry and to date entry) , a button and CrystalReportViewer control to your form.



using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

            TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
            TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
            ConnectionInfo crConnectionInfo = new ConnectionInfo();
            Tables CrTables;

            ParameterFieldDefinitions crParameterFieldDefinitions ;
            ParameterFieldDefinition crParameterFieldDefinition ;
            ParameterValues crParameterValues = new ParameterValues();
            ParameterDiscreteValue crParameterDiscreteValue = new ParameterDiscreteValue();

            crParameterDiscreteValue.Value = textBox1.Text;
            crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
            crParameterFieldDefinition = crParameterFieldDefinitions["fromDate"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Clear();
            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            crParameterDiscreteValue.Value = textBox2.Text;
            crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields;
            crParameterFieldDefinition = crParameterFieldDefinitions["toDate"];
            crParameterValues = crParameterFieldDefinition.CurrentValues;

            crParameterValues.Add(crParameterDiscreteValue);
            crParameterFieldDefinition.ApplyCurrentValues(crParameterValues);

            crConnectionInfo.ServerName = "YOUR SERVERNAME";
            crConnectionInfo.DatabaseName = "DATABASE NAME";
            crConnectionInfo.UserID = "USERID";
            crConnectionInfo.Password = "PASSWORD";

            CrTables = cryRpt.Database.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
            {
                crtableLogoninfo = CrTable.LogOnInfo;
                crtableLogoninfo.ConnectionInfo = crConnectionInfo;
                CrTable.ApplyLogOnInfo(crtableLogoninfo);
            }

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

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
The Crystal Reports file path in your project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal Reports file like c:\projects\crystalreports\CrystalReport1.rpt
crConnectionInfo.ServerName = "YOUR SERVERNAME";


  crConnectionInfo.DatabaseName = "DATABASE NAME";


  crConnectionInfo.UserID = "USERID";


  crConnectionInfo.Password = "PASSWORD";

You have to pass the necessary database connection information.

Now you can run the program . Enter from date and to date , then you can see the report whose order date is between from date and to date you passed to Crystal reports.

csharp-crystal-reports-date-to-date

How to Crystal Report Merge Module

The following section shows how to create a setup file for Crystal Reports Client side installations using Merge Modules.
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
In the previous section How to install C# Crystal Reports on Clinet machine , we already saw how to deploy a Crystal Reports components and assemblies on the target machine using CRRedist2005_x86.msi file. Here we are creating a separate setup file for client side installations using Crystal Report Merge Modules.
Crystal Reports uses merge modules to ensure the correct report components and assemblies are installed with your deployment of C# project. A merge module is a set of components that are merged with a Windows installer for applications that need them. The following steps are creating a setup file for Crystal Reports Client side installation using Merge Modules.
Before creating a setup project, make sure that the following files exist in the \Program Files\Common Files\Merge Modules folder.
CrystalReportsRedist2005_x86.msm
  Microsoft_VC80_ATL_x86.msm
policy_8_0_Microsoft_VC80_ATL_x86.msm
Steps to create Setup file for your C# Application.
1) Make sure the above mentioned files are in the \Program Files\Common Files\Merge Modules folder , If the files are not there you can download the file and copy it to the folder \Program Files\Common Files\Merge Modules .
Download: https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/11688
2) Open your Visual Studio
3) Select "New Project" from File menu.
crystal-reports-deploymet-1
4) Select "Setup and Deployment" from "Other Project Types"
5) In the "Solution Explorer", select your setup project, right-click, and select Add and Merge Module from the menu.
crystal-reports-merge-module
6) Select CrystalReportsRedist2005_x86.msm to your setup project.
The file available at \Program Files\Common Files\Merge Modules
crystal-reports-merge-module-files
Then you can see Microsoft_VC80_ATL_x86.msm and policy_8_0_Microsoft_VC80_ATL_x86.msm will be automatically added in the Detected Decencies section.
7) Build your project.
Now you will get the setup file for distribution. Either you can add this setup file to your C# application installer or distribute it as a separate setup file.

How to deploy Crystal Report

The following section describes how to deploy a Crystal Reports components and assemblies on the target machine.
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
Crystal Reports for Visual Studio ships with your deployment projects that enable you to deploy Crystal Reports components and assemblies on the target machine. We can use different approaches to install Crystal Reports runtime files on the target machine in order to run your C# applications smoothly.
If you are using Visual Studio then during your setup and deployment you can add the CRRedist2005_x86.msi file to your setup file and distribute it as a single setup file with your C# application. The installer can execute the setup file automatically within your .Net Project in a single click. You can find the CRRedist2005_x86.msi file in your system's C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages\CrystalReports . Also you can distribute the CRRedist2005_x86.msi separately and install it on the target machine where your C# applications installed.
The other way to install Crystal Reports on target machine is to create a setup file using Merge Modules and distribute it with your C# application or as a separate setup file. Click the following link to see how to make a setup file with Merge Modules.


How to print Crystal Reports in C#

The following program shows how to print multiple copies of Crystal reports from C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
The following program generate a Crystal Reports from product table and print 2 copies of report without using CrystalReportViewer in C#. The program generate report from Product table , the step by step tutorial for creating a Crystal Reports from C# section explains how to create report from Product table. Also the program dynamically passing the logon parameters to Crystal Report. If you don't know how to pass dynamic logon parameter please take a look at the section C# Dynamic logon parameters in Crystal Reports.
Hope you understand the previous section well. Create a Crystal report from Product Table and copy and paste the following source code in the project.


sing System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load("PUT CRYSTAL REPORT PATH HERE\CrystalReport1.rpt");

            TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
            TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
            ConnectionInfo crConnectionInfo = new ConnectionInfo();
            Tables CrTables;

            crConnectionInfo.ServerName = "YOUR SERVERNAME";
            crConnectionInfo.DatabaseName = "DATABASE NAME";
            crConnectionInfo.UserID = "USERID";
            crConnectionInfo.Password = "PASSWORD";

            CrTables = cryRpt.Database.Tables;
            foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
            {
                crtableLogoninfo = CrTable.LogOnInfo;
                crtableLogoninfo.ConnectionInfo = crConnectionInfo;
                CrTable.ApplyLogOnInfo(crtableLogoninfo);
            }

            cryRpt.Refresh();
            cryRpt.PrintToPrinter(2, true, 1, 2);

        }
   }
}

cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
The Crystal Reports file path in your project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal Reports file like c:\projects\crystalreports\CrystalReport1.rpt


  crConnectionInfo.ServerName = "YOUR SERVERNAME";


  crConnectionInfo.DatabaseName = "DATABASE NAME";


  crConnectionInfo.UserID = "USERID";


  crConnectionInfo.Password = "PASSWORD";


You have to pass the necessary database connection information.

Now you can run the program . When you run this program the program will print multiple copies of Crystal Reports.



5 Tests for Top Performance by Jason Dove

Summary: How to improve the efficiency of any Crystal Report using one or more of the five steps in this article.
5 Tests for Top Performance
It is complete, your masterpiece report. Not only does it meet your customer's expectations, it blows them out the water, all they want is beautifully summarised and displayed in a myriad of ways.
Then
Disaster!
You try to run the report for a month against the live database and not the two days test data you used for development.
Suddenly your report's runtime goes from twenty seconds to two hours.
Every Crystal Reports developer has experienced this situation and it can be one of the most frustrating aspects of report design.
Thankfully there are a variety of things that can be done to combat bad performance, any one of which can reap huge benefits.
Here are the five most likely causes of poor performance and how to mitigate their effects.
1. The Database Set Up
This may or may not be within your direct control to alter, but databases are not set up ideally.
Two top contenders are:
a: The fields you are filtering on are not indexed. You can check whether or not this is the case by referring to the Linking Tab in the Database Expert window. Indexed fields have colored markers next to them.
I have personally seen reports run hundreds of times quicker due to the addition of an index being added to an important (to the report filter) field.
b: Using a view rather than a table to report from can be devastating to a report's performance. This is mainly due to views not having indexes. A view is a collection of tables (much like a basic report) and is often used to simplify data for end users.
The only way to avoid this is to report on the tables which make up the view. Identifying whether the source of a field is a table or a view can be done via the Database Expert as tables and views are listed separately.
Identifying which tables make up a view can be much trickier and you may need the help of the database documentation.
Also, when using Oracle databases, turning off the case sensitive option on queries can really speed up reporting times but may require existing reports to be rewritten.
2.Using the wrong ODBC driver.
ODBC drivers are how Crystal Reports attaches to the database. There is usually a variety of ODBC drivers which will work for any particular make of database and some are better than others.
The only way to really test this is to run the report with all the suitable ODBC drivers and see which is the most efficient.
Experience has taught me that the ODBC driver provided with the software associated to the database is usually the best option.
3.Excessive Use of Sub Reports
Each sub report is like another report accessing the database, and if that sub report is placed in the Detail Section it will run for EVERY record the main report loads. Even if placed in a Group Section the sub report will still be run numerous times.
Report Sections are usually the ideal place to home a sub report as they will only run once. But this still turns one report into two as far as performance is concerned.
The best way to negate the performance issue caused by sub reports is to not use them.
Ninety nine percent of sub reports are not necessary and the same result can be achieved using other methods through grouping, running totals and / or formulas.
4.Table Linking
Anything other than a Link Type of equals ('=') will cause a massive degradation in performance.
The Link Options window (accessible through right clicking on a specific link) will allow any values to be reset.
If there is a need for this time of link, the same result can be achieved through the Group Selection or through formatting (and hiding the unwanted records) once they are loaded into the report.
5. Record Selection
When code for the record selection is written correctly, Crystal Reports will pass all the logic to the database as SQL and only return the data needed.
If the record selection is not written in an SQL friendly way, Crystal Reports will bring back all the data and then filter it locally. This can be drastically slower than when calculated on the database.
Using the Record Selector Expert will guarantee that any filter created will be evaluated on the database and be as efficient as possible.
An additional point which can make a difference in some cases is when the report is scheduled to run. Heavy network traffic or database usage can impact a report's running time.
Working through the above points will enhance the efficiency of your slowly running reports. Building your reports with all this in mind from the beginning will save you redevelopment time later.

C# Crystal Reports - sub reports

The following progrm describes how to create a sub report within a Crystal Report in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
Subreport in Crystal Reports means that a report inside a Crystal Report . When we want to show some additional information about a data field in a Crystal Reports row, we use the subreports features to show the details. We can display sub report in two ways , one is to show subreport directly under the main row details. The other method is to show it as C# Crystal Reports on demand sub-reports , that means we put an Hyper link just below the row filed , and when the user click that hyper link it will show the subreport.
In this section we are going to generate a sub-report under the main row details. That is for each row there is a subreoprt for the details.
csharp-crystal-report-subreport-final
Here we are going create an order report based on three tables in the database and show a subreoprt for each row field of Product Name. Here we are using our earlier program C# Crystal Reports from multiple tables to show the main Crystal Reports Data , so refer C# Crystal Reports from multiple tables , before start this section .
Create a Crystal Reports using three tables and select customername , date , product and qty . It will explain in detail the previous section C# Crystal Reports from multiple tables.
Next step is to create a sub report inside the main report. Here we are showing the Product details in each row of the specified product in the main row.
After create the main report , right click on Crystal Reports designer window and select Insert-Subreport.
csharp-crystal-report-insert-subreport
Then you will get the subreport object , drag the object in the designer window at the down part of the details tab , just below the fields in the details tab. When you release the mouse you will get a dialogue box asking report name . Enter a report name , and click the Report Wizard Button .
The wizard shows the table selection screen and select the table . Here in this case we have to select the Product Table from the list and click next .
Next screen is showing the table , from there select the fields you want to show the data and click finish. The you will get the sub report main screen again and select Link tab .
The link tab is making relation with your main Report and subreport . Here we are linking the productname from main report to the subreport. For that select Product.Product_name from Available fields.
csharp-crystal-report-link-subreport
Accept the other settings as it is in the screen and click ok. Now you can see the sub report object in the screen , if you want to re-arrange subreport design , double click on subreport object then you can design subreport.
csharp-crystal-subreport-design
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;


using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
            crystalReportViewer1.ReportSource = cryRpt;
            crystalReportViewer1.Refresh();
        }
    }
}

C# Crystal Reports - sub reports

The following progrm describes how to create a sub report within a Crystal Report in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
Subreport in Crystal Reports means that a report inside a Crystal Report . When we want to show some additional information about a data field in a Crystal Reports row, we use the subreports features to show the details. We can display sub report in two ways , one is to show subreport directly under the main row details. The other method is to show it as C# Crystal Reports on demand sub-reports , that means we put an Hyper link just below the row filed , and when the user click that hyper link it will show the subreport.
In this section we are going to generate a sub-report under the main row details. That is for each row there is a subreoprt for the details.
csharp-crystal-report-subreport-final
Here we are going create an order report based on three tables in the database and show a subreoprt for each row field of Product Name. Here we are using our earlier program C# Crystal Reports from multiple tables to show the main Crystal Reports Data , so refer C# Crystal Reports from multiple tables , before start this section .
Create a Crystal Reports using three tables and select customername , date , product and qty . It will explain in detail the previous section C# Crystal Reports from multiple tables.
Next step is to create a sub report inside the main report. Here we are showing the Product details in each row of the specified product in the main row.
After create the main report , right click on Crystal Reports designer window and select Insert-Subreport.
csharp-crystal-report-insert-subreport
Then you will get the subreport object , drag the object in the designer window at the down part of the details tab , just below the fields in the details tab. When you release the mouse you will get a dialogue box asking report name . Enter a report name , and click the Report Wizard Button .
The wizard shows the table selection screen and select the table . Here in this case we have to select the Product Table from the list and click next .
Next screen is showing the table , from there select the fields you want to show the data and click finish. The you will get the sub report main screen again and select Link tab .
The link tab is making relation with your main Report and subreport . Here we are linking the productname from main report to the subreport. For that select Product.Product_name from Available fields.
csharp-crystal-report-link-subreport
Accept the other settings as it is in the screen and click ok. Now you can see the sub report object in the screen , if you want to re-arrange subreport design , double click on subreport object then you can design subreport.
csharp-crystal-subreport-design
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

C# Crystal Reports from XML

Usually we are generating Crystal Reports from Databases , here in the following section describes how to create a Crystal reports from XML file in C#. This is very similar to creating Crystal Reports from database , the only difference is that you have to select the data source as the XML file at the designing time of Crystal Report in C#.
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
In order to generating Crystal Report from XML file , we have to create an XML file . Here we are going to create an XML file and name it as Product.XML . The structure of the Product.XML file is same as the Product table in the crystaldb database earlier mentioned in this section C# crystaldb . The content of the product.xml is shown below.
csharp-crystal-report-product-xml
Generating Crystal Report from XML file is very similar to generating Crystal Report from Databases. The only difference is happened when you selecting the datasource part. Here you have to select Create New Connection - Database Files and select the XML file you want to generate Crystal Reports (In this case you select the Product.xml ).
csharp-crystal-report-xml-select
Select all the fields from Product and click finish button
Now the designing part is over and the next step is to call the Crystal Reports in C# and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;


using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReportDocument cryRpt = new ReportDocument();
            cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");
            crystalReportViewer1.ReportSource = cryRpt;
            crystalReportViewer1.Refresh();
        }
    }
}

NOTES:
cryRpt.Load(PUT CRYSTAL REPORT PATH HERE\\CrystalReport1.rpt");

The Crystal Reports file path in your C# project files location, there you can see CrystalReport1.rpt . So give the full path name of Crystal Reports file like c:\projects\crystalreports\CrystalReport1.rpt
 

C# Crystal Reports from SQL Query

The following section describes how to create a Crystal Reports in C# using SQL Query String .
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
Generating a Strongly Typed DataSet
Here we are using a Strongly Typed Dataset for generating a Crystal Reports from SQL Query string . Before start this section , you can take look at the previous section of how to create a C# Crystal Report from Strongly Typed Dataset. Because here we are using Strongly Typed Dataset for generating Crystal Report from SQL Query string.
Here we are generating a report against the Product table . So we are passing the following sql and generating the report
sql = "SELECT Product_id,Product_name,Product_price FROM Product";
Create a new C# project and create a new Strongly Typed Dataset from Project - Add New Item Dialogue Box.
Add three column in the Strongly Typed Dataset .
Product_id
  Product_name
Product_price
csharp-crystal-report-dataset-product
Create a new Crystal Report and select DataTable as Data Source . You can select DataTable from the wizard , Project Data - ADO.NET Dataset - Crystal report Dataset1 - dataset1. Click the Next Button.
csharp-crystal-report-select-product
Select fields ( Product_id , Product_name , Product_price ) from the next screen and click the finish button. Then you will get the designer screen with the selected fields. If you do not know how to create a dataset , refer the previous section How to create a C# Crystal Report from Strongly Typed Dataset.
Now the designing part is over. From the source code we can pass the SQL source code to Crystal Reports.
Select the default form (Form1.cs) you created in C# and drag a button and a CrystalReportViewer control to your form .
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient ;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn ;
            string connectionString = null;
            string sql = null;

            connectionString = "data source=SERVERNAME;initial catalog=DATABASENAME;user id=USERNAME;password=PASSWORD;";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = "SELECT Product_id,Product_name,Product_price FROM Product";
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet1 ds = new DataSet1();
            dscmd.Fill(ds, "Product");
            MessageBox.Show (ds.Tables[1].Rows.Count.ToString());
            cnn.Close();

            CrystalReport1 objRpt = new CrystalReport1();
            objRpt.SetDataSource(ds.Tables[1]);
            crystalReportViewer1.ReportSource = objRpt;
            crystalReportViewer1.Refresh();
        }
    }
}

connectionString = "data source=SERVERNAME;initial catalog=DATABASENAME;user id=USERNAME;password=PASSWORD;";
You have to provide the necessary database information to Connection String.
 

Dynamic Crystal Reports from C# Application

Usually Crystal Reports generating with pre-defined columns . That is, the fields showing in Crystal Reports are selecting through a wizard at the time of Crystal Report design.
The following program describes how to generate a Crystal Report in C# with dynamic columns at the time of report generation . That is, we are not selecting any column from database table at the time of Crystal Report design. Instead of that we are passing an SQl query string and get the Crystal Report dynamically at runtime in C# . From the following picture you can understand how it works.
csharp-crystal-report-dynamic-column
All C# Crystal Reports Tutorial in this website is based on the following database - crystaldb. So before you begin this section , please take a look at the database structure of crystaldb - Click Here C# crystaldb
If you are new to Crystal Reports and do not know how to create Crystal Reports from C# , please take a look at the section step by step tutorial for creating a Crystal Reports from C#.
Here we are going to create a Dynamic Crystal Report with the help of Strongly Typed Dataset. Create a new CSharp project and add a Strongly Typed Dataset in the C# Project . Before creating a Strongly Typed Dataset take a look at the detailed tutorial of how to create a C# Crystal Report from Strongly Typed Dataset of previous section .
Hope you understand how to create a C# Crystal Report from Strongly Typed Dataset. Create a new C# project and add a Strongly Typed Datset . Add five columns in the DataTable of Strongly Typed Dataset. Here we are limiting as five column , but you can add any number of column according to your reports requirements.
csharp-crystal-dynamic-column
Next step is to create a Crystal Reports design from the Strongly Typed dataset. You have to add a Crystal Report in your project and select data source as Strongly Typed Dataset. If you don't know how to do this section , refer the previous section of How to create a C# Crystal Report from Strongly Typed Dataset.
csharp-crystal-report-dynamic-table
Select all the column (five) from Strongly Typed Dataset .
csharp-crystal-report-dynamic-column-selection
Click finish button . Then you can see the selected fields in the Crystal Repots . Arrange the fields according to your requirement . Now the designing part is over and the next step is to call the Crystal Reports in CSharp and view it in Crystal Reports Viewer control .
Select the default form (Form1.cs) you created in CSharp and drag a Textbox , button and CrystalReportViewer control to your form (like in the first picture ).
Here we are going to pass the SQl statements to Crystal Reports at runtime from C# program . For that we have to parse the SQL statement before we passing it to Crystal Reports. So we create a function for parsing SQL statements in the C# program.
Public Function procesSQL() As String
You have to include CrystalDecisions.CrystalReports.Engine in your C# Source Code.
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;

using System;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Data;
using System.Data.SqlClient ;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        CrystalReport1 objRpt = new CrystalReport1(); 

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection cnn ;
            string connectionString = null;
            string sql = null;
            connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;";
            cnn = new SqlConnection(connectionString);
            cnn.Open();
            sql = procesSQL();
            SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
            DataSet1 ds = new DataSet1();
            dscmd.Fill(ds, "Product");
            objRpt.SetDataSource(ds.Tables[1]);
            crystalReportViewer1.ReportSource = objRpt;
            crystalReportViewer1.Refresh();
        }

        public string procesSQL()
        {
            string sql = null;
            string inSql = null;
            string firstPart = null;
            string lastPart = null;
            int selectStart = 0;
            int fromStart = 0;
            string[] fields = null;
            string[] sep = { "," };
            int i = 0;
            TextObject MyText ;

            inSql = textBox1.Text;
            inSql = inSql.ToUpper();

            selectStart = inSql.IndexOf("SELECT");
            fromStart = inSql.IndexOf("FROM");
            selectStart = selectStart + 6;
            firstPart = inSql.Substring(selectStart, (fromStart - selectStart));
            lastPart = inSql.Substring(fromStart, inSql.Length - fromStart);

            fields = firstPart.Split(',');
            firstPart = "";
            for (i = 0; i <= fields.Length - 1; i++)
            {
                if (i > 0)
                {
                    firstPart = firstPart + ", " + fields[i].ToString() + " AS COLUMN" + (i + 1);
                    firstPart.Trim();

                    MyText = (TextObject) objRpt.ReportDefinition.ReportObjects[i+1];
                    MyText.Text = fields[i].ToString();
                }
                else
                {
                    firstPart = firstPart + fields[i].ToString() + " AS COLUMN" + (i + 1);
                    firstPart.Trim();

                    MyText = (TextObject)objRpt.ReportDefinition.ReportObjects[i+1];
                    MyText.Text = fields[i].ToString();
                }
            }
            sql = "SELECT " + firstPart + " " + lastPart;
            return sql;
        } 
    }
}

connectionString = "data source=SERVER NAME;initial catalog=crystaldb;user id=USER NAME;password=PASSWORD;";
You have to provide the necessary database information to Connection String.