How to dynamically load images in crystal report

In this post I will show how to display images dynamically on crystal report.  If you store images in your database in a binary format, there could be two approaches to display them on a crystal report.  One approach is to read image from database in a byte array and then write image on your hard disk and then load images from the path. The second approach is to read the image from database and directly display it on crystal report. Second approach looks better to me as there will be no IO operation. And it will be more efficient.

Let’s start the work. I don’t have a database at the moment with me. So what I will do is that I will read an image from disk and convert it into byte array and then pass it to crystal report. I hope this will not matter if we read image from database or a disk.

I create a new window project and name it ImagesInRpt. Add a new crystal report in the project. I name the report “rptImages”. In the next dialog window select blank report and press ok.

rptImages_1

 

rptImages_2

Next we will read an Image from the disk and convert it into bytes. And then create a DataTable and store image in it. And then we will create schema file and design report from schema file. On the Form1 I added one button ‘Load Report’ and on its click event a schema file is created. So that we can design the reports.

rptImages_3

rptImages_4

As you can see the on the click even we call a method which return a data table. We created two column in the data table one is Img of data type System.Byte[], and the other one is ImgName of data type System.String. The we create XML schema file and stored it on the disk. Next we will design the report from this schema file.

Open the report and right click on database fields to open the Database expert from Field Explorer. Create a new connection as shown below. And select ADO.Net.

rptImages_5

 

This will open another window. Select the schema file, in our case we created it on the D drive of our hard disk. After selecting the file click on finish button.

rptImages_6

 

Next you can see the column names on the field explorer in under database fields. Drag the column on your report and do some formatting. Now on the form drap the CrystalReportViewer and ReportDocument control on the form. Next we read the image and add it the datatable in the form of bytes. And pass the data table to crystal report viewer. On the button click event I commented the line which generates XML schema file. We no more need that file as the purpose of creating this file is only to design the report.

rptImages_7

 

rptImages_8

 

 

 

 

Now run the application and you can see once you click on the Report Load button, the report gets loaded.

rptImages_9

You can download the source code from the following location ImagesInRpt-SourceCode


 

Tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

*