We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 19
4 LEVEL EXTREME
J
INNOVATION TO A HIGHER LEVEL
Level éxeme pasform
‘subscription
Corporate profile
Products & Services
Support
Legal
Francis
sear Search
Feeding Crystal Reports from your apelication
Eric Moreau, September 1, 2006
“This clu wil not show you how to place controls ona report, How te format
fle, neither now to distribute reports. The toples have been narrowed to the
‘communication Between your current application and the reparts you are
bling. The version tate used nee is the version of Crystal Repo,
SUMMARY
‘This column wl not show you how te place controls on a report, how to format flds, nether how to disibute
reports, The topics have ben narrowed tothe commun cation between your current application andthe reporss
you ae building. The version thats used ere i the version of Crystal Reports that comes uncles wit Visual
Sto 205.
DESCRIPTION
‘This marth, decided to revel some secrets about Crystal Reports Infact, Ihave decided to wrt becouse this
article wil answer many cuestions found into newsgroups.
‘This column wl not show you how to place control on a repart,how to format lds, nether how to dlsibute
reports, The topics have been narrowed tothe communication between your current appliaton andthe reports
you are builing.
“The version that is used heres the version of Crystal Reports that comes bundled with Vist Studlo 2005,
Wich version of Crystal Reports do we have?
‘The version that comes bundled into Visual tuto 2005 (Professional edtion and above) sa special immed
Gown version ofthe version 10(somethingike 10.2) Ifyou tink that some features are missing, you can havea
look at here to find what the ful version has more te of. This version includes a customized designer that
fully integrate in Visual Studio Vial Studio 2005 fr report cesign. You may use the integrated designer to
create epors for usein your Visual Stuclo 2008 applications. these applcazons are Windows applications, the
runtime can be distributed freely to any numberof end user's PC fs abitiferen for Wed apps. You can reads
fullicansing data fom hace. relly tink that fr mr of your nesce, the bunaled varson wll be mere hen
rou
Planning your report
Before going to creare your report. you need to answer a couple of questions. Some of these question:
+ cancrystalReports conecttomy data source?
*+ ss my presentation layer shaving adrect accesso the database or does ithas to go through a data layer?
+ Doyou need to adéadstional ata (calculation or transformation to what you find in your database?
+ Dol prefer to feed my repar from a class instance already loaded?
There are many ways of passing data toa report. My favorite method of al ime has alas been to pass. ll
_aataset(a cecanset inthe DAO/ADO eraliathe cepa This isthe metned that wll be used inthis lum. This
‘method: us ceateon-the.ly data to be printed Italsolet us modifies or summarizes eur main source. Very
fen, we already have a dataset in memory containing the data we want print so wy re-query the database?
Ifyou preferto connect your reports decry ta your database, you may tl find ater sections ofthis article
interesting becouse everything elses the same.
Preparing data forthe report
‘As sai earlier, my favorite method isco feed a report frm a dataset | already have or that create onthe fy.
Some extra tape are required inorder tod tie way ike creating a schema forthe dataset,
‘So my demo application has auton tiled “reate data Source, This button creates a dataset that contains 2
Gatatables (one for countries and one for states lead data into both datatables ard crate a relation between
these rao tables. Al hiss done without any database the dea here sto get a dataset no matter how ts ed,‘Yourow need to create a schema from this dataset. The easiest way todos to use the WeitexMLchema
‘method from your dataset. This is what tre button titled “Create schema is ding
sata eta sehea(“: emp\oeesehena es)
Embedsed or nat?
‘Younaw have another decision to make, This decison snot risky one as an be easily mod ter. The
reports that you are creating with she designer can ether be dstrbuted as a standalone report (rps fle or as
‘comple (aka ernbeddea within your project (exe ar
by default, reports that you add to @ projec are aded as embedded resource (se figure). you want to use
standalone repo fies, change the “bul action” property to None.
wet
EEE ctiromice
Cpynoeetores ort apy
‘The adontage ofan embeded report is hat you dont have a series of report fs to sstrbute andthe end
users cannet matify them. The disadvantage i tha ifa report needed o be modified, the project that embeds
the report needs tobe recompiled and redeployed
Personal | prefer to distribute he report les as standalone les in fat simply copy the reper fles on a
serve and all applcacons ae loading the report fom there. you need to change a smal hig Ike 2 font or 8
size, you dant need te bulé and publish, you just have to save and coay. Users dant even need to stp the
application and restarItn order tage your modifeaion.
Creasinga project for your reports
“Another hint: instead of adding my reports tothe same project sally classes, | always create 3 new project
that ony contains my reports and he schemas ale remove the bulls property rom the Configuration
‘Manager so that projects never compiles
| normally use the “Crystal Reports Appear” template fr tis particular prec asa the required references
are automaticaly ade. normally open the Configuration Manager sialog rom the Bull menu) anc remove
the Bull option fortis projec (see igure 2.
‘Toth’srew projec, add the scherna you created in the previous sep. This canbe done by drag and dropping
{from Windows explorer to your projet name) or by using “Add + Exsting tem.” on your project
Adeing a report to your project
"Now that we have the data ready and the schema, we can now creat the report To get the Crystal Reports
‘esigner, you need toads a report to a projec in your solution. This can be easily done by using the "Add New
Item." rom tne"Projec menu, The"Add New te claleg wil then be shown to you see igure 3). From the Ist
‘of templates, select “Crystal Repor change the Nome to Something mearingful have set io rptTestrpXl and
lick te Ads burtonre
‘sol sto stoed tangas
Boren re odes eer ran
Sperm Bete Sesame
San en Berean Senn
Bose foe Bette
Seren Buscres
(ttertcdrom eeraercrent Powered
Avocent, Beoraetie Serer
ete Bousoaren athe
isthe Burne rere
Senos a) Rloreren
enn Sjictatincovtaasenth yuri corent
Byhaake Os ayrnsae saves
Acrsaseprt at puke 2310 Yeauns WTO”
ses ‘Boat
‘Then he Crystal Reports Gallery wizard wil tart and askyou forthe type ofreporcto create, Accept he
{etault options (Using the report ward and Standard) and lk the OK burton
‘Then the*Standaré Report Creation Wizard wil be shown. Thats where you need to bind your current report to
yur eata source ar to your schema. nan eae step, we have prepared a XML schema. Tis schema has been
aude to the same project that contain the report. This schema is now avalable under “Project Data - ADO NET
DataSets (ee gure 4}. Using the acrane inthe mile ofthe dialog, add bath tables (countries and state) to
the sof seletes tabs
After having clicked the Next buon, youwil et she wizard wil gt you to the Link step. this case, you simely
reed to clk the Next button because we have aleady done our relatin through the code an the XML schema
Inthe Fels step ofthe wizard, simply add al els tothe st of elds to Olsplay’ and cick the Nex button.
Inthe Grouping step, select "Countries Description” a the fet on which to group by and click the Finish button
The Crystal Reports designer wil finaly aspay your repor (se igure). would now be the perfec time to set
the "Build Action” property to None,ees =x
[Groups tome
Testing your report
LEE EE EE EE,
Before staring o customize the report. laways ike to test Our main projet the ane that includes a form is
nat ready yet to test the report, You fist need toads viewer te the main application. From your toolbox. find
the Crystal Reports tb, select the rystalRepoctViewer (se igure 6) and place ane on your form.
Figur: igs eet or,
ysl Regots
Ie ter
2 Fooetccat|
“Yournow need to write a couple af Ines of code in order to load a report pass a dataset othe report and display
Ie into the ewer nse the code you nese:
ores sppieat in Startagath &“\rpTart98*)
rpc starasnure(esaata)
fuss the gor Oocurent chject to the viewer
Youalso need to define your mrptDoc variable at the top of your class Ike tis
‘ut wat before running the sample application’ Ifyou carefully look athe calito the Load method ofthe
RepertDacument abject, you willsee thatthe application i expecting to find ale named rptTestptin the
startup folder (usual bin\debug at ths ime) You can set ths path tobe anywhere but the poi that you
eed copy your standalone repor files otha folder Otherwise, aload report exception willbe raises. You
also need to insure that the datasets files otherwise you wil get alogin prompt on the screen. you do these 2
requirements, you shoule see your report coming to viewer with the data created manually.
"Now that the eportis shown correctly, you can now eustomize the report o.be more good looking, One realy
ice thing about using standalone reports that you can eat yur reports using the designer of Visual Stulo
wienout having to stop your application, save, recopy ico the right fold’ and finaly get Back your
application press the preview button. Thats make the process of testing changes 9 report alt fester hen
having to recompile the application each ime!
Passing a value toa report obect
es really easy to feed an object Ike the lTexcObject with a value om your application. | often do that fr report
tie 1am often able to use the same report layout as the Basis for many final reports and then I need a way to
printa tle dynamically on the repory, The wick here isto use the ReportsObjectcallection to acess one
‘lementof the report and give a value ot
Before ooking atthe code that does that, add a TextObject to your report (by right-clicking the reper, selecting
Insert then Text Object and cleking on your report to pasion Like any athe abject. because you Want to
access through code, you should give ths objec a significant name by sting the (Name) property (something
ae nee,
Here's a helper metho that canbe used to set the Text property of any TenObject of loaded report
Private Su Apiytettbsect(syal steTetabject AS Str
byt vetvortalue to String)
Cypetertoneteporton nketon.Resrtonecteostrenesbeet),
ceysatbectotoecrystalapars, agin Texeobjct) ant =ressageon-Shwt"aplyTexcobject” & Enviroment eine & =
share Aba nt 8 vrtrontyeet
secenect In tas repost)
"This method can now be called lke ths before sting the RepotSource of your vewer:
‘pplentObjectttite’, "Your tle goeshere")
The rst parameters the name ofthe objet found in your report. The second parameters he value to gve to
this object. This method is curently setting the Text property but ust about any property could bese
‘he downlcadable demo even contains similar method that canbe used ta set ITectbect from a sub-eport
{the methoe i named ApplySubReportTetObjec, When you cl this method, you nee to specify the name of
the sub-reportin dation to the name othe abject ane the value
Passing avalue toa parameter of se report
You might lo want to pass values toa reper that comes from the user interface or a database or any other
source) and use that value‘o iter o” format your report. For examole, we will add a tiveshold parameter tothe
report and use ito set the BackColor property of the population felt
We rst need to adda parameter to our report. Todo this insure that your reports curently in the designer
and that you can see the "eld Explorer of Crystal Reports (f you dont se i select the Crystal Reports menu
and ck Fel Explore) nthe Feld Explorer, rightclick Parameter Fees" and select New. Adal led "Create
Parameter Fel" wll be cisplayed (see nigur 7-In this alo, Set the Name fel to somethirg meaning ike
PopulatonThreshol) and select the correct value ype (a numiser in his case). When you are done, cckthe OK
button
ne
‘ante
tere
lira vate
cen)
Onree vi platelets
oe
We wl ow use this parameter to change the BackColor ofthe Population field Start by righ he
Population fle on your report and selecting "Format abject from the concexten. From the Format Editor,
‘ent the Border tab To the righ of"Backyround? there Is abutton (on which yu can see X+2) that allows you
tw enter formula, lik ont. Inthe bottom pare of the Formula Workshop dalog see figure, encer this
fermala(this formula ses the background color tore f the value of the Population felis higher then the
parameter vale otherwise, the background is eto white) an click the Save and close button:
5 (Staes.Population) > Poqutaiontivesnis) then
by earn fy
Sb
1S Ste Peter
Z Snwi aps Corian
E FepstteetanctSitePond
E Goeth comnsedeneo
I eepstntraa
a Tesbase PODRET)
« q a | ve
ipo aus ‘ana
cto es‘The las thing you need to do ito passa value tothe parameter. A singe ine of code is required te do that. Ts
line mus: be called before seting the ReportSource of your viewer Ike this
epacSetrarmetenatee-Populatintirstate, Some)
The frst parameter isthe name of the parameter found In your report. The second parameters the value to ge
to this parameter.
Ifyou run your application again (dnt forget to copy your report), you shouldbe able to see that some states
have cere background color re
Free Walthroughs
Business Objects (the company behind Crystal Reports) created a 581 pages walkthroughs tat can be
‘owloaded for free rom here, The sales ofthese walkthroughs ae also availabe for free downoad rom
here I strongly suggest you download these
Conclusion
[really think tat tis atl gives you a fast (out complet) geting starced method to create your frst reports
with custom data alg th sie methoes of setting abjects properties and parameters You can goa let
deeper in Crystal Reports asitisauge product
‘nope you appreciated the topic and see you next month
Source cade
ricMoreau, Moer ne
Eric Moreau i an independent contractor. He holds tre Mcrosft Certs Solution
Developer (CSD) certircation andi ls a Visual Developer - Visual Base MVP es
mainly programming cientiserver applications using VBNVENet and MS SQLServer (and all
the stuff surcounding particularly inthe nancial inaustry, He work with VB since
version 4 and teaenes it since version 5. Hei mamber ofthe Montreal Visual Stusio User
{Group (wera uv net) where he pues some sessions, He sao # speaker athe
Deviesen conferences ince its beginning in 2003.
[MORE ARTICLES FROM THIS AUTHOR
ric Moreau, january 1, 2006
ould change the fonts used by the Messageox, oF how he could translate the
Messageton siappear alter 10 secondo” hom. think you already kn that
‘Alder Browser clog (in Windows Forms)
Wie often nees to have users use “olser browser dialog in our appiations,
‘You surly already have used the Win32ShBrowseForFolderfurcton when
bling VO6 applications? Guess what, Microsofe Visual Studio.Net team forgot
this feature when they bul .Net 2002! There are at last
‘Accepticg parzmeters fra VB application
IF you nees to pass parameters to your application use the Command function
‘Acding Cut, Copy, Faste, Lindo ard Delete command support
Using oh SenaMessageA API call you can implemen these features ita any
applieasons.‘Acdicg plugins ta your zcplications
ic Moreau, August, 2005
Have you ever thnk of extending a application aleasy distributed? Have you
ver thine of string some madules or featres of your appiations ony to
some users or cents?
‘Ac Action List componect
Fre Moreau, August, 2007
‘This component sa kindof delegate that let you do aperations he settings
properties or reacong to vents fr mare shan a single GUI elemant ot your
form. Ths way, you can realy decouple Ul elements fom the code
‘scimaticg ie ican when the for is micirzed
Fie Moreau, Jy 3, 2001
Supsose you want a form to perform a task while minim geo then notify the
User nithout a message box and while ramairing minimizes, You can do this by
hanging the con on the minimize fem nthe taskbar. Tne same code can also
be used fora noneminimized form as wll
‘Agglications Settings in VBNEt
‘il Windows applications need to persist some data, Here can thin of tee
diferent kings of data, The rs kns of dts normaly kept into a database. An
pplication hos been cteated to handle that data feustomers, veces, Bs,
utrors, won talk abou thar kine of data inthis a
‘AnaSettings revisited
fri alrady covered this sue forthe Framewor® 1, so this time he doesnt
‘spend any time aking about other ways of storing aplcatons andor using
settings ater than what available inthe ConiurationSetings ass. This ass
was great enhanced in Net 20,
‘Associate an anclication to an extension,
Fie Moreau, Jy, 2001
Tohve your application launch whenever a fle with a particular extension is
Double-cicked, you need to reser your application with that extension inthe
Registry (CLASSES_ROOT Hive) here's short wrapper function | pu together
tnd use Fortis purpose:
lenkccate nto the Date Time Pier
Fre Moreau, September 20,20
‘The greatest feature ofthe Date Time Picker conztl valle fom he
Merosof Windoms Common Controle? 60) shat the sate vale is aay 2
dates. By setting the CustomFormat property oa space, you are able to 26
callamathod bys nee,
fre Morenu, Apr 28,2001
eis posite calla functon/sub if he ony cue you have ofthe funeton i its
‘cD-cve's door: Open and lose it
frie Moreau, Jy 72001
Sometimes, you request te user to insert a CD inte drive, You can helo the
ser by already opening she doer for him for her) sing te Winsows
Mutemedia DL worm, you can open and close tne CD drive's doar rom
{your application. Note that not all she CD aves support these functions‘Code clegnastic(ar eicle on tracing and debueine)
The Debug and she race classes belong othe System Diagnostics namespace
‘These are the to classes you need te know tobe able a either Debug or Trace
your apes
oreo ly 1, 2005
For mary mnths, many of my users, the oldest in particular, were complaining
‘that controls are harly readable when these same cantros are not enable,
Fach time Iwas tling them that 12 not able te do much abou that since it
‘normal bnaviour of contrale
‘Sombahox: Setting the aximum length
ic Moreau, July, 2001
‘The ComboBox contol doesnt havea MaxLength property Ie the TextSox
cantrol does. Yau can add some cade to emulate tis property. Notice that you
canis coue only the KeyPress event You also ned zo program the Change event
{cis event il or allow users to paste longer strings ta your conta
‘Combatiowes io Windows Forms DateGriss
Fie Morea, Jaary 1, 2003
Iw uznor 2s new monthly column in which wl inreduce you to teples
‘mainly related to Windows Forms into the Visual Baie Net environment i
«ute large to spend many months without rambling. The suggested formats 2
Single topiin about 2 pages long (0 that you can reat fos)
‘Soman dialogs
ores une 2003
‘los all applications need to ask uses to open or save ale. You may want 0
stort building your on for olla but this este is rectly aval fom
Windows ris accessible cough a single Commmen Dal contra rom VBSIS oF
‘through specialized controls from visual stusio Net
‘Compression inthe Net Fremework2.0
‘The version 2.6 ofthe Net Framework has asded builtin compression features
rarely tne Detatestream class ana the GZpStream cas. These new features
are part ofthe Sytem 10.Compression namespace
‘Coay menu fram ore apalicaton to anather
oreo May 2,001
Because menu definition is not cage inte a form and sna a contrl on a form,
{yu cannot easly