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;
Copy and paste the following source code and run your C# project
Download Source CodePrint Source Code
Free Ajax Application Generator!
Generate data entry and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!
Looking at Distributed Data Grids?
Today�s developers have discovered that distributed data grids unleash application performance and scalability. Try ScaleOut StateServer� and give your apps a boost. Download a free evaluation copy!

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.

Create a Crystal Report Visual studio

Crystal Reports has been a part of Visual Basic since 1993, and a part of Visual Studio since its first release in 2002. Crystal Reports has been a very successful component of these products. With the release of Visual Studio 2010, SAP and Microsoft have mutually decided to change how we deliver this important component to the .NET developer community going forward.

Starting on Friday, April 16th, the beta version of Crystal Reports for Visual Studio 2010 will be available as a separate download from this site.  Just like when Crystal Reports was integrated into the  Visual Studio installation, this download will continue to be free.

Crystal Reports for Visual Studio 2010 will contain many new features compared to Crystal Reports Basic for Visual Studio 2008.  This blog on the SAP Developer Network goes into more detail on the new features and how they benefit report designers, .NET developers, and report consumers.

Both SAP and Microsoft believe this change in delivery method will allow for faster innovation of our respective products, and more value for our mutual customers.  

In this video you can see how to create a crystal report in C#.

 

MapForce

Need an easy way to get data into XML, or transform XML to another format? MapForce lets you map XML data to/from any combination of XML, database, flat file, Excel 2007, XBRL, or Web services data. Then it transforms data instantly or auto-generates royalty-free code for recurrent conversions. New features in Version 2011!
  • Easy-to-use, graphical data mapping interface
  • Instant data transformation
  • XSLT 1.0/2.0 and XQuery code generation
  • Java, C#, and C++ code generation
  • Advanced data processing functions
  • Support for all major relational databases including SQL Server, IBM DB2, Oracle, and more
  • Integration with Altova StyleVision for report rendering
  • Visual Studio & Eclipse integration
  • Available in 32-bit and 64-bit versions
Altova MapForce
Download a fully-functional trial today!

DataGridView

The DataGridView is a control designed to be bound to database tables. You will find the DataGridView in the Data group on your Toolbox. In this section, we will use the DataGridView to build a SQL interface for the Northwind Trader database. This application is surprisingly simple using the classes provided by ADO.NET.

Figure 15.5

Image:Figure15_5.jpg
To create the user interface, place a TextBox on the form and set its Multiline property to true. Then, add two buttons, setting their Text properties to Query and Update. Finally, place a DataGridView component on the form. Your form might look something like the one in Figure 15.5.
Since we are going to connect to a Microsoft Access database, we need to use the OleDb classes. At the top of the file, you should add the following using statement to gain access to the System.Data.OleDb namespace.
using System.Data.OleDb;
The Form’s Load event should create an OleDbConnection object, an OleDbCommand object, and a DataSet object. Each of these objects should be stored as members of your Form class.
private void Form1_Load(object sender, EventArgs e) {
   // connect to the database
   string conString =
      @"Provider=Microsoft.JET.OLEDB.4.0;"
      + @"data source=c:\data\Northwind.mdb";
 
   // create an open the connection          
   conn = new OleDbConnection(conString);
   command = conn.CreateCommand();
 
   // create the DataSet
   DataSet ds = new DataSet();
   }
Next, you need to implement the select button’s Click handler. The method should start by clearing the DataSource property of the DataViewGrid and creating a fresh DataSet. Then, it should reopen the connection. Set the Command object’s CommandText property to the Text from the TextBox control. Then, create an adapter with the command and fill the new DataSet. Finally, set the DataGridView’s DataSource property to the first table in the DataSet’s Table collection.
private void button1_Click(object sender, EventArgs e) {
   // clear the grids data source
   dataGridView1.DataSource = null;
 
   // create a new DataSet
   ds = new DataSet();
 
   // open the connection
   conn.Open();
 
   // run the query
   command.CommandText = textBox1.Text;
   adapter = new OleDbDataAdapter(command);
   adapter.Fill(ds);
    
   // close the connection
   conn.Close();
 
   // set the grid's data source
   dataGridView1.DataSource = ds.Tables[0];
   }
The last step is to implement the Click event handler for the Update button.
private void button2_Click(object sender, EventArgs e) {
   // clear the grids data source
   dataGridView1.DataSource = null;
 
   // open the connection
   conn.Open();
 
   // run the query
   command.CommandText = textBox1.Text;
 
   int affected = command.ExecuteNonQuery();
   MessageBox.Show ("There were " + affected + " rows affected");
 
   // close the connection
   conn.Close();
   }
The update button sets the DataGridView’s DataSource property to null to clear the grid. Then, it reopens the connection and sets the command object’s CommandText property to whatever text is in the TextBox. This time the command is executed by the ExecuteNonQuery method. The ExecuteNonQuery method runs a command that updates or deletes records. It returns the number of rows affected by the command. Finally, the method displays a message box showing the number of rows affected and then closes the connection. Figure 15.6 shows a SELECT statement being executed on the database.

Figure 15.6

Image:Figure15_6.jpg
Figure 15.7 shows the update button being used to change the ContactTitle from Guru to Fool.

Figure 15.7

Image:Figure15_7.jpg
To verify that our update actually worked, we can run the query again.

Figure 15.8

Image:Figure15_8.jpg

Java Word Count

Word Count Example in Java

This example illustrates how to count the number of lines, number of words and number of characters in the specified file. Program takes the file name as parameter and it counts the number of words and lines present in the file. Parameter is optional and if you simply run the program without mentioning the file name then you will have to input some strings and program will count the number of characters and number of words for your given strings. This topic is related to the I/O (input/output) of java.io package.
In this example we are using FileReader class of java.io package. The File class is an abstract representation of file and directory pathnames.

Explanation
This program counts the number of lines, number of words and number of characters in the specified file. We will be declaring two functions called wordcount and linecount in the program. The function linecount has been overloaded according to the passing argument. If you input contents through the file then linecount function will be called (If specified file exists) otherwise main function counts the number of characters and number of lines (always, the number of line will be only 1 in this condition) itself but for the counting of the number of words by using the wordcount function.

wordcount(String line)
The function wordcount(String line) takes either the content of the specified file or arguments passed with the run command for a java program as parameter 'String line'. The wordcount() function is using arrayname.charAt(index) to find position of space in the string.  A counter variable 'numWords' is used to count the number of words.

linecount(String fileName);
The function linecount(String fileName) takes the specified file name as a string parameter and create a instance for the FileReader class to buffering then the file or string and it is passed to the function linecount(String fName, BufferedReader in).

linecount(String fileName, BufferedReader);
The function linecount(String fName, BufferedReader in) takes the specified file name and created instance in for the BufferedReader class by calling function linecount(String fileName) and assign the content of the buffer in a string variable line. And then the function linecount(String fileName, BufferedReader) counts and print the number of characters, number of lines. To count the number of words call the wordcount(String line) function.

Code of the Program : 
import java.io.*;

public class  WordCount{
  private static void linecount(String fName, BufferedReader in) 
  throws 
IOException{
  long numChar = 0;
  long numLine=0;
  long numWords = 0;
  String line;
    do{
      line = in.readLine();
      if (line != null){
        numChar += line.length();
        numWords += wordcount(line);
        numLine++;
      }
    }while(line != null);
    System.out.println("File Name: " + fName);
    System.out.println("Number of characters: " + numChar);
    System.out.println("Number of words: " + numWords);
    System.out.println("Number of Lines: " + numLine);
  }
  private static void linecount(String fileName){
    BufferedReader in = null;
    try{
      FileReader fileReader = new FileReader(fileName);
      in = new BufferedReader(fileReader);
      linecount(fileName,in);
    }
    catch(IOException e){
      e.printStackTrace();
    }
  }
  private static long wordcount(String line){
    long numWords = 0;
    int index = 0;
    boolean prevWhiteSpace = true;
    while(index < line.length()){
      char c = line.charAt(index++);
      boolean currWhiteSpace = Character.isWhitespace(c);
      if(prevWhiteSpace && !currWhiteSpace){
        numWords++;
      }
      prevWhiteSpace = currWhiteSpace;
    }
    return numWords;
  }
  public static void main(String[] args){
    long numChar = 0;
    long numLine=0;
    String line;
    try{
      if (args.length == 0)
      {
        BufferedReader in =
        new BufferedReader(new InputStreamReader(System.in));
        line = in.readLine();
        numChar = line.length();
        if (numChar != 0){
          numLine=1;
        }
        System.out.println("Number of characters: " + numChar);
        System.out.println("Number of words: " + wordcount(line));
        System.out.println("Number of lines: " + numLine);
      }else{
        for(int i = 0; i < args.length; i++){
          linecount(args[i]);
        }
      }
    }
    catch(IOException e){
      e.printStackTrace();
    }
  }
}