Showing posts with label Crystal Reports. Show all posts
Showing posts with label Crystal Reports. Show all posts
0

Crystal Reports Display Images From Database Asp.Net

This example explains how to Add Show Display Logo Pictures Images In Crystal Reports Dynamically From Sql Server DataBase In Asp.Net 2.0,3.5,4.0. There are two scenarios to achieve this task.

1. When images are saved in sql server database.

2. When pictures are saved on server and name or path is saved in database.


I'll explain both cases one by one.
Display Images In Crystal Reports From Database



1. Displaying From Database
Step 1. Upload And Save Images In SqlServer DB Using FileUpload Control by following the link.

Step 2. Right click on solution explorer and select add new item >Add DataSet and name it DataSet1.


Step 3. Right click on dataset designer window and select Add DataTable and rename it as reportTable.


Step 4. Right click on DataTable and select Add > Column.
Add 3 columns ID,Name,Image and define datatype in properties windows as System.Decimal for ID ,System.String for Name, and System.Byte[] for binary column respectively and save it.



Step 5. Right click on solution explorer > Add new Item > Crystal Report



Select Project Data > ADO.NET DataSets > reportTable from available datasources and add it to right pane.


Add All the fields in right pane in next window and click on finish.


Now Drag the Image field from field explorer on crystal report.


Step 6. Add CrystalReportViewer from toolbox to Default.aspx page.

Choose CrystalReportSource1 and CrystalReport.rpt from next dialog boxes.



HTML SOURCE OF PAGE WILL LOOK LIKE
   1:  <CR:CrystalReportViewer ID="CrystalReportViewer1" 
   2:                          runat="server" 
   3:                          AutoDataBind="True" 
   4:                          ReportSourceID="CrystalReportSource1"/>
   5:  <CR:CrystalReportSource ID="CrystalReportSource1" 
   6:                          runat="server">
   7:               <Report FileName="CrystalReport.rpt"/>
   8:  </CR:CrystalReportSource>

Write below mentioned code in Page_Load Event of Default.aspx page in code behind to fetch the data from databse and fill the Dataset.

C# CODE
using System;
using System.Data.SqlClient;
using System.Configuration;
using CrystalDecisions.CrystalReports.Engine;

protected void Page_Load(object sender, EventArgs e)
    {
        //Create object of dataset1.xsd we created earlier in design mode 
        DataSet1 dsReport = new DataSet1();
        
        //Create SQL Connection And Command And Fill DataSet1
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        string strSelect = "SELECT ID,Name,Image FROM Img";
        SqlCommand cmd = new SqlCommand(strSelect, con);
        SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
        con.Open();
        dAdapter.Fill(dsReport.Tables["reportTable"]);
        con.Close();

        //Set Report Source
        ReportDocument crystalReport = new ReportDocument();
        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
        crystalReport.SetDataSource(dsReport);
        CrystalReportViewer1.ReportSource = crystalReport;
    }

VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim dsReport As New DataSet1()
 Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
 Dim strSelect As String = "SELECT ID,Name,Image FROM Img"
 Dim cmd As New SqlCommand(strSelect, con)
 Dim dAdapter As New SqlDataAdapter(cmd)
 con.Open()
 dAdapter.Fill(dsReport.Tables("reportTable"))
 con.Close()
 Dim crystalReport As New ReportDocument()
 crystalReport.Load(Server.MapPath("CrystalReport.rpt"))
 crystalReport.SetDataSource(dsReport)
 CrystalReportViewer1.ReportSource = crystalReport
End Sub

Build and run the application.

2. Add Pictures From server.
Follow Steps 2 to 6 as mentioned above and save image name or path in sql server as shown below.


Write below mentioned code in code behind.

C# CODE
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using CrystalDecisions.CrystalReports.Engine;
using System.IO;
protected void Page_Load(object sender, EventArgs e)
    {
        DataSet1 imageDataSet = new DataSet1();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        string strSelect = "SELECT ID,Name FROM Img";
        SqlCommand cmd = new SqlCommand(strSelect, con);
        SqlDataAdapter dAdapter = new SqlDataAdapter(cmd);
        con.Open();
        dAdapter.Fill(imageDataSet.Tables["reportTable"]);
        con.Close();

        for (int rowNumber = 0; rowNumber < imageDataSet.Tables["reportTable"].Rows.Count; rowNumber++)
        {
            string imgName = Server.MapPath(imageDataSet.Tables["reportTable"].Rows[rowNumber]["Name"].ToString());
            DisplayImages(imageDataSet.Tables["reportTable"].Rows[rowNumber], "Image", imgName);
        }

        ReportDocument crystalReport = new ReportDocument();
        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));
        crystalReport.SetDataSource(imageDataSet.Tables["reportTable"]);
        CrystalReportViewer1.ReportSource = crystalReport;
    }
    private void DisplayImages(DataRow row, string img, string ImagePath)
    {
        FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
        byte[] ImgData = new byte[stream.Length];
        stream.Read(ImgData, 0, Convert.ToInt32(stream.Length));
        stream.Close();
        row[img] = ImgData;
    }
VB.NET CODE
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim imageDataSet As New DataSet1()
 Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
 Dim strSelect As String = "SELECT ID,Name FROM Img"
 Dim cmd As New SqlCommand(strSelect, con)
 Dim dAdapter As New SqlDataAdapter(cmd)
 con.Open()
 dAdapter.Fill(imageDataSet.Tables("reportTable"))
 con.Close()

 For rowNumber As Integer = 0 To imageDataSet.Tables("reportTable").Rows.Count - 1
  Dim imgName As String = Server.MapPath(imageDataSet.Tables("reportTable").Rows(rowNumber)("Name").ToString())
  DisplayImages(imageDataSet.Tables("reportTable").Rows(rowNumber), "Image", imgName)
 Next

 Dim crystalReport As New ReportDocument()
 crystalReport.Load(Server.MapPath("CrystalReport.rpt"))
 crystalReport.SetDataSource(imageDataSet.Tables("reportTable"))
 CrystalReportViewer1.ReportSource = crystalReport
End Sub
Private Sub DisplayImages(row As DataRow, Img As String, path As String)
 Dim stream As New FileStream(path, FileMode.Open, FileAccess.Read)
 Dim ImgData As Byte() = New Byte(stream.Length - 1) {}
 stream.Read(ImgData, 0, Convert.ToInt32(stream.Length))
 stream.Close()
 row(Img) = ImgData
End Sub
Build and run the application

Download Sample Code


2

Export Crystal Reports To PDF Word Excel In Asp.Net

This example explains how to Export or Save Crystal Reports To Pdf,Ms Word,Excel Programmatically In Asp.Net

Export crystal reports to pdf word excel in asp.net


For this Example i have used Northwind Database and Employees table.

After you have finished Creating Crystal Reports,

place one button on the aspx page to export report to pdf or word format.

We'll write code in Page_Load Event to load report when page loads and in Click Event of button to create pdf,word or excel report.

HTML SOURCE OF PAGE
   1:  <form id="form1" runat="server">
   2:  <div>
   3:  <asp:Button ID="btnExport" runat="server" 
   4:              Text="Export To PDF" 
   5:              onclick="btnExport_Click"/>
   6:  </div>
   7:  <div>
   8:  <CR:CrystalReportSource ID="CrystalReportSource1" 
   9:                          runat="server">
  10:      <Report FileName="ExportToPdf.rpt">
  11:      </Report>
  12:  </CR:CrystalReportSource>
  13:      
  14:  <CR:CrystalReportViewer ID="CrystalReportViewer1" 
  15:                          runat="server" 
  16:                          AutoDataBind="True" 
  17:                          EnableDatabaseLogonPrompt="False" 
  18:                          EnableParameterPrompt="False" 
  19:                          ReportSourceID="CrystalReportSource1"/>
  20:  </div>
  21:  </form>


C#
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
protected void Page_Load(object sender, EventArgs e)
    {
        ReportDocument pdfReport = new ReportDocument();
        pdfReport.Load(Server.MapPath("ExportToPdf.rpt"));
        pdfReport.SetDatabaseLogon("amitjain","password", @"AMITJAIN\SQL", "Northwind");
        CrystalReportViewer1.ReportSource = pdfReport;
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        ReportDocument pdfReport = new ReportDocument();
        pdfReport.Load(Server.MapPath("ExportToPdf.rpt"));
        pdfReport.SetDatabaseLogon("amitjain", "password", @"AMITJAIN\SQL", "Northwind");
        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();
        pdfReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Employees");
        Response.End();
    }


VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim pdfReport As New ReportDocument()
 pdfReport.Load(Server.MapPath("ExportToPdf.rpt"))
 pdfReport.SetDatabaseLogon("amitjain", "password", "AMITJAIN\SQL", "Northwind")
 CrystalReportViewer1.ReportSource = pdfReport
End Sub
Protected Sub btnExport_Click(sender As Object, e As EventArgs)
 Dim pdfReport As New ReportDocument()
 pdfReport.Load(Server.MapPath("ExportToPdf.rpt"))
 pdfReport.SetDatabaseLogon("amitjain", "password", "AMITJAIN\SQL", "Northwind")
 Response.Buffer = False
 Response.ClearContent()
 Response.ClearHeaders()
 pdfReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, True, "Employees")
 Response.[End]()
End Sub

Build and run the code.

To Export crystal Reports to Word Excel or other formats we need to change below mentioned line of code to desired format.

For MS WORD
pdfReport.ExportToHttpResponse(ExportFormatType.WordForWindows, Response, true, "Employees");

Where Employees is the name of file you want to be created.

For MS Excel
pdfReport.ExportToHttpResponse(ExportFormatType.Excel, Response, true, "Employees");


5

Pass Crystal Report Parameters Programmatically Asp.Net

Pass Crystal Report Parameters Programmatically In Asp.Net 2.0,3.5,4.0 Using C# And VB.NET. In this post i am explaining how to pass parameters to crystal reports programmatically in code behind of asp.net web page.

Pass Crystal Report Parameters Programmatically In Asp.Net

For this example i am using northwind database and products table.

I have put one text box on the page and report will display details of product based on product id entered by user.

Read how to create Crystal Reports In Asp.Net , Or Windows Forms.


Open crystal report in design view, right click on it and select Field Explorer

Now select Parameter Fields and select new to add new parameter to report.

Name it as ProductID and remember it.

Now click on Special Fields in Field Explorer and select Record Selection Formula.

Select is equal to and {?ProductID} from the dropdowns and click on OK.

Click on smart tag of reportviewer control and uncheck Database logon prompting and parameter prompting as we will provide these info in code behind.


HTML markup of aspx page

<form id="form1" runat="server">
    <table class="style1">
        <tr>
            <td>
                Enter Product ID :
            </td>
            <td>
                <asp:TextBox ID="txtProductID" runat="server">
                </asp:TextBox>
                </td>
            <td>
                <asp:Button ID="btnReport" runat="server" 
                            Text="Show Report" 
                            onclick="btnReport_Click" 
                            Width="108px" />
                </td>
        </tr>
    </table>
    <br />
    <CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" 
        AutoDataBind="True" EnableDatabaseLogonPrompt="False" 
        EnableParameterPrompt="False" Height="1039px" 
        ReportSourceID="CrystalReportSource1" 
        ReuseParameterValuesOnRefresh="True" 
        Width="901px" DisplayGroupTree="False" />
    <CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
        <Report FileName="CrystalReport.rpt">
        </Report>
    </CR:CrystalReportSource>
    </form>


Now go to code behind of the page and add below mentioned namespace for crystal reports.

using CrystalDecisions.Shared;
using CrystalDecisions.CrystalReports.Engine;

Write this code in Page_Load event of the page

protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack) CrystalReportViewer1.Visible = true;
        else
            CrystalReportViewer1.Visible = false;
    }

Generate click event for button to shaow report and write this code.

protected void btnReport_Click(object sender, EventArgs e)
    {   //Create report document
        ReportDocument crystalReport = new ReportDocument();
        
        //Load crystal report made in design view
        crystalReport.Load(Server.MapPath("CrystalReport.rpt"));

        //Set DataBase Login Info
        crystalReport.SetDatabaseLogon
            ("amitjain", "password", @"AMITJAIN\SQL", "Northwind");

        //Provide parameter values
        crystalReport.SetParameterValue("ProductID", txtProductID.Text);
        CrystalReportViewer1.ReportSource = crystalReport;
    }

Build the solution and run.


have fun.

13

SubReport In Crystal Reports

In this example i am going to describe how to Create SubReports in Crystal Reports or Crystal Reports SubReport in ASP.NET Using C# And VB.NET. For this i have used two tables from MS SQL database named Employees and Projects.
Main Crystal Report is fetching data from both the tables and is grouped by Project Name

SubReport is used to display information about respective project and fetching data from Projects Table.

Schema for both the tables in shown below in images, create tables accordingly and add relevant data in it to start.


You can click on Images to Enlarge 

 
  
To start , Create a new website in VS and right click on Solution Explorer and select Add new Item > Crystal Report. In the wizard window choose Using the Report Wizard radio button and Standard type in Choose an Expert section.

 
In next screen select Expand OLEDB(ADO) and Choose create new connection 

 
Select Microsoft OLEDB Provider for SQL server and click next 

 
In next screen check the Integrated security checkbox so that report doesn't ask for username and password  Enter you SQL Server name and Select DataBase from the dropdown ,

 
In next window expand and locate your tables you want to use and add them in right pane 

 
  
In next screen select the fields you want to display in main report and add them in right pane , in my case i am showing fields from two tables in main report 
 Now select the field which you want report to be grouped by ( in this example i m grouping report by Project Name)

Select the report style you want and finish the wizard 

 Now to add a subReport Right click in group header section (below Group #1 Name) 
Choose Insert > SubReport , Place the ractangle where you want SubReport to be displayed. a wizard window will open prompltly

 
Enter report Name and click on report wizard buttonin next screen ,
  
  
  
Choose the table and fields you want to use in SubReport in next two screens and click on finish 
Now Insert subReport window will open again , In this window click on Link Tab and select the field on which you want to filter SubReport or the ID of the record to show SubReport. I am using ProjectID in this example.

This is how design of report will look like 

 
And this is how report preview will look

 
Save , build and rum the website. 
Now if you don't want to show SubReport but want to put a hyperlink instead or want to create On-Demand SubReport then do these changes in the design of report 
Right click on SubReport in Design View and select Format Object 

 
In the window opened ,Go to SubReport tab, Change the SubReport name to text you want to show as hyperlink, Check the On-demand SubReport check box and click on ok 
 
 
Now design of report will look like image below 

 

On default.aspx page drag CrystalReportViewer from toolbox and assign CrystalReport we just created as source
Html source will go like this (AutoGenerated)
<CR:CrystalReportViewer ID="CrystalReportViewer1" runat="server" 
                        AutoDataBind="True" Height="1039px" 
                        ReportSourceID="CrystalReportSource1" 
                        Width="901px" />
<CR:CrystalReportSource ID="CrystalReportSource1" runat="server">
<Report FileName="CrystalReport.rpt">
</Report>
</CR:CrystalReportSource>

Save, build and run the solution , this is how Crystal Report SubReport will look like


Hope this helps.

22

Crystal Reports In Winforms Windows Forms With Parameters

In this example i am explaining how to create Crystal Reports In Winforms Or Windows Forms Application With Parameters from user to filter report using C#.NET and VB.NET

Crystal Reports In Winforms Or Windows Forms Application With Parameters
For this i have created two tables in database named Employees and Projects and fetching data from both tables

I've grouped results by Department name using group expert in crystal reports and put a dropdown on the form to select project name to display related report.

Employee table schema

ID    int  
FirstName    varchar(50)
LastName    varchar(50)   
Department    varchar(50)   
ProjectID    numeric(18, 0)  
Expenses    money   


Projects table schema 

ProjectID    numeric(18, 0)   
ProjectName    varchar(50)  









Create a new project in VS and go to solution explorer and add new item > crystal report.
Select Blank report option from the wizard window
 
Now click on CrystalReports menu and select DataBase Expert 
Now in next window expand Create new connection section and OLEDB(ADO) and in next window select SQL Native Client

Enter you SQL Server name , username and password , select database name from the dropdown and click on ok
In next window expand to find your tables and add them in right pane
Click OK to finish

Now Right Click on Group Name Fields in Field Explorer and Select Group Expert.
In group expert box select the field on which you want data to be grouped.
 
  
Design your report by dragging the fields in section3 (Details) 
my design look like this  
In the form add a combobox and drag and drop CrystalReport Viewer from toobox. click on smart tag and choose the report we created earlier (CrystalReport1.rpt) 
Form look like this 
When we build and rum this report , it asks for Database login username and password , we need to provide database username and password in code behind.
 we need to write code in code behind to filter report based on user selected value or value provided by user 
C# code behind
//Code to populate dropdown
//Fill dropdown in form_Load event by calling 
//function written below
private void FillDropDown()
{
 SqlConnection con = new SqlConnection
       (ConfigurationManager.AppSettings["myConnection"]);
 SqlCommand cmd = new SqlCommand
("Select distinct ProjectID,ProjectName from Projects", con);
 con.Open();
 DataSet objDs = new DataSet();
 SqlDataAdapter dAdapter = new SqlDataAdapter();
 dAdapter.SelectCommand = cmd;
 dAdapter.Fill(objDs);
 cmbMonth.DataSource = objDs.Tables[0];
 cmbMonth.DisplayMember = "ProjectName";
 cmbMonth.ValueMember = "ProjectID";
 cmbMonth.SelectedIndex = 0;
}
private void cmbMonth_SelectedIndexChanged
              (object sender, EventArgs e)
{
      //Create object of report 
CrystalReport1 objReport = new CrystalReport1();

    //set database login information
objReport.SetDatabaseLogon
    ("amit", "password", @"AVDHESH\SQLEXPRESS", "TestDB");

//write formula to pass parameters to report 
crystalReportViewer1.SelectionFormula 
    ="{Projects.ProjectID} =" +cmbMonth.SelectedIndex;
crystalReportViewer1.ReportSource = objReport;
}
      

VB.NET code behind
Private Sub FillDropDown()
    Dim con As New SqlConnection
   (ConfigurationManager.AppSettings("myConnection"))

    Dim cmd As New SqlCommand
("Select distinct ProjectID,ProjectName from Projects", con)
    con.Open()
    Dim objDs As New DataSet()
    Dim dAdapter As New SqlDataAdapter()
    dAdapter.SelectCommand = cmd
    dAdapter.Fill(objDs)
    cmbMonth.DataSource = objDs.Tables(0)
    cmbMonth.DisplayMember = "ProjectName"
    cmbMonth.ValueMember = "ProjectID"
    cmbMonth.SelectedIndex = 0
End Sub

Private Sub cmbMonth_SelectedIndexChanged
(ByVal sender As Object, ByVal e As EventArgs)
    
    'Create object of report 
    Dim objReport As New CrystalReport1()
    
    'set database login information
    objReport.SetDatabaseLogon
("amit", "password", "AVDHESH\SQLEXPRESS", "TestDB")
    
    'write formula to pass parameters to report 
    crystalReportViewer1.SelectionFormula 
= "{Projects.ProjectID} =" & cmbMonth.SelectedIndex

    crystalReportViewer1.ReportSource = objReport
End Sub

Hope this helps

Download sample code



other articles on Crystal reports and winforms
Creating Crystal reports in ASP.NET C# VB.NET

Creating winforms AutoComplete TextBox using C# in Windows application

OpenFileDialog in winforms windows forms C# .NET VB.NET windows application

SubReports in Crystal Reports in ASP.NET

Find More Articles