Click here to Skip to main content
Click here to Skip to main content

Dynamic Reports UsingSQL Queries

By , 23 Nov 2005
 

Sample Image

Sample Image- Multilines

Introduction

Microsoft Visual Studio .NET provides Crystal Reports for report printing and throws the DataReport component (Visual Studio 6) away from .NET. Although, Crystal Reports is a good report creator, sometimes when we want to create dynamic reports, maybe for listing something or for data summation, it is not so suitable. Crystal Reports can be used for dynamic reports but it has a fixed set of column types and the number of maximum columns.

So I use the PrintDocument component, in the System.Drawing.Printing namespace of the .NET base library. PrintDocument is a component like a plain paper. You can draw or print anything on it. Normally, you have to set the object coordination and other properties just like when you use a pen to write on the paper. But for this code, you just use a SQL query or a dataset only!

Using the code

Add a form to a project and a PrintDocument component to it. And use a DataSet, and specify the column of the first table (Table(0)) by strict format (1 set per 1 report column):

  • Column 1 -> Column name.
  • Column 2 -> Start position on paper, I set that all width has range between 0-99.
  • Column 3 -> End position on paper, I set that all width has range between 0-99.
  • Column 4 -> Justify (L-Left, R-Right, C-Center).
  • Column 5 -> Has summarize in this column (Y/N).
  • Column 6 -> Display format (such as #,##0.00).
  • Column 7 -> Rest in line? Begin with 1.
  • Column 8 -> Data column.

Please look at the example, it's easy to understand.

We can set the properties of PageSetDlg and prnSetDlg objects for the print options. I use the Form component and I put the PrintDocument, PrintPreviewDialog, PageSetupDialog, and PrintDialog components on it. Then, we can use these for direct printing or use a print dialog too. We can set the properties of those objects for a specific print option such as setting the page orientation to landscape, etc.

'-------- Example use, If you haved data in
'           dataset already. --------------

'--- We can set properties of PageSetDlg
    ' and prnSetDlg object for print option 
    'frmDynamicPrint.PageSetDlg.PageSettings.Landscape = True

    '---If it has sum column is this report,
    '   we have to set hasSum flag to true. 
    frmDynamicPrint.hasSum = True

'---Initialization
    frmDynamicPrint.FontName = "Tahoma"
    frmDynamicPrint.FontSize = 12
    frmDynamicPrint.FontSizeHead = 16
    frmDynamicPrint.FontSizeHead2 = 14
    frmDynamicPrint.LineHeight = 1
    frmDynamicPrint.SkipLinePerRecord = 1

    '---Call InitPrint for inital some properties,
    ' you can modify it.
    frmDynamicPrint.InitPrint()

    frmDynamicPrint.HeadFirstString = _
      "Report for Product Order Value Summary"
    frmDynamicPrint.HeadSecondString = "Test Report"
    frmDynamicPrint.DateString = Now.ToString
    frmDynamicPrint.PrintPreview()
    frmDynamicPrint.Dispose()

Points of Interest

I will develop an HTML report later or will add a feature to export a report to another format.

History

  • November 27, 2005 - Fixed a little bug in the example in setting the page number.
  • November 24, 2005 - Fixed a big bug in the query loop and the summation method. I'm very sorry for my late bug fixing.
  • October 05, 2005 - Added the wrap text feature.
  • September 13, 2005 - Add feature for multiple lines and setting height of each line. It can be used like the wrap text feature too.
  • September 12, 2005 - Changed the column position addressing on paper. Use start-end positions instead of one position.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Pakorn Indhatep
Web Developer
Thailand Thailand
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionC#???memberrobertdlm18 Jul '12 - 17:57 
can you post in C#??
QuestionDisplaying the values of fieldmemberElie Ghanoum19 May '08 - 11:48 
after I got the values of certain field. it always display them in vertical way. How can I display them in horizontal way
GeneralError on printing - Infinity page print!!!memberMember 179106330 Mar '08 - 22:49 
Hi,
 
When I tried to print first time, i got an error saying "there is no date at row ##" then i insert the fallowing lines into prnDoc_PrintPage function
 

PageNumber = 0
SumList.Clear()
dbCursor = 0L
 

There's the actual problem comes up, it try to print infinity number of pages, last page number I saw was 986 which is kinda infinity already for 2 page report I guess.I should also say that all pages are the first page, non of these 986 pages contains any data from the second page! Frown | :(
 
PS: i didn't actually print them on paper, I just saved the output as PDF file. Smile | :)
GeneralNew comer Need Help...PleasememberSamRST22 Sep '07 - 20:01 
Hi friends,
i'm new in windows application. can u please give me an idea about the crystal report generation. i searched lot but in confusion..different articles in different ways.. help me please
cheers..
GeneralDbnull Values and Columns Not found after Countmemberjcviera6 Feb '07 - 7:37 
I tried using this with a Stored Procedure and Filling the dbset with an adapter I used from my object and that all worked but It gave me the error that it could not find Column 46 but there is no Column 46 so what do I do now?
 
Error was: out of Range Exception
 
thanks,
 
Jason
GeneralSource code Bugsmemberdanmarin9 Dec '06 - 7:39 
There is a swarm of bugs in this code, unfortunately it is a nice piece of code , but it should be fixed so that others can take a chance at it.
First of all:
1) The document does not print, i guess it goes beyond the end of the dataset as the message is "there is no row at position 72"
2) If you try the "fixes" proposed here it will just loop infinitely
3) It is a huge chunk of code , it should be broken down in small units in order to read it properly.
4) if you try to comment any of the try-catch structures the document crashes "method not supported" this means that with the try -catch mechanism suppresses some other error.
 
Hope this feedback helps and also i hope you still want to edit this post as it is a promising piece of code, nice idea as you tried to approach it from a different angle.
 
Hope for a fast feedback.
 
Dan
.NET DEVELOPER
 
"The universe and the developers were always in a war. Developers trying to create idiot-proof programs and the universe creating idiots. The universe seems to win....D'Oh! | :doh: Frown | :( img src="/script/Forums/Images/smiley_doh.gif" align="top" alt="D'Oh! | :doh:" />
GeneralPage NumbersmemberRichard Elias11 Sep '06 - 22:02 
I noticed that the pagenumber is not increased while having multiple pages.
This could be fixed in the same area that resets dbCursor
I solved it in the following manner and that works fine, including printing and reprinting.
If hasSum Then
If Not (dbCursor = dbSet.Tables(0).Rows.Count) And (Not printSumComplete) Then
e.HasMorePages = True
PageNumber += 1
Else
e.HasMorePages = False
dbCursor = 0
PageNumber = 1
End If
Else
If Not (dbCursor = dbSet.Tables(0).Rows.Count) Then
e.HasMorePages = True
PageNumber += 1
Else
e.HasMorePages = False
dbCursor = 0
PageNumber = 1
End If
End If
 
Richard
GeneralPrint problemmemberRichard Elias11 Sep '06 - 3:02 
Dear Pakorn,
 
If you want to print the preview, an error occurs on table boudaries.
This is caused by the dbCursor that follows the datatable.
The problem can be overcome by resetting dbCursor fter the last page is printed.
If hasSum Then
If Not (dbCursor = dbSet.Tables(0).Rows.Count) And (Not printSumComplete) Then
e.HasMorePages = True
Else
e.HasMorePages = False
dbCursor = 0
End If
Else
If Not (dbCursor = dbSet.Tables(0).Rows.Count) Then
e.HasMorePages = True
Else
e.HasMorePages = False
dbCursor = 0
End If
End If
 
If the dbCursor = 0 line is inserted in both scenarios, I am now able to reprint the report as often as I want.
 
Hope this is of help.
 
With kind regsrd,
 

 
Richard Elias

QuestionPage header & footer?memberpoetyip24 Aug '06 - 5:40 
I am wondering if this dynamic report can have something like pageheader or pagefooter? It is because I have 2 db want to print. The header would like to put in pageheader, and detail in your normal details section.
Questioncan't print multiple page problemmemberTony567887657 Jul '06 - 6:46 
When I click the print button, if the report page more than 1,
there is a message box "Generating Preview" show "page xxx of document" never stop, I think it's a recursive loop.
I don't know how to fix this problem.
Thanks a lot!
GeneralReport Inflated on Printed Copymemberhing_jl15 May '06 - 21:59 
I tried to print the report to printer. When I looked at print preview, it was perfectly OK. I tried to print via pdf writer. I worked fine.
 
However, when I printed directly to printer, the page was inflated, i.e., the computer seemed to print on a A4 X 120% paper. Printing was OK on Left and Top Margin but was not OK on Right & Bottom margin. I temporarily fixed it by changing Bottom and Right margin to a larger number.
 
I do not have the inflated printing problem using MS Words, Excel & etc.
 
Does anymore have this problem?
 
I used Windows 2000. fyi
 
-- modified at 4:01 Tuesday 16th May, 2006
QuestionHow to Group Data in Report?membersricse27 Mar '06 - 7:52 
Hi,
Thanks For Posting Such a Great Code!
But I have a small problem. I need to group the data as per a Customer Name and print it similar to the following format in the same report.
Ex:Dispalying the Invoice Details Per Each Customer
 
Customer Name:Abc
SNo. Items Itemname Price
1 4 Blade $11
2 2 Paper $2
 
Customer Name:XYZ
SNo. Items Itemname Price
1 2 Candies $10
2 2 Dolls $24
 
etc.
 
Pls help me to figure it out.
Thanks in Advance
Sri
AnswerRe: How to Group Data in Report?memberbryantlaw9 Jan '07 - 20:50 
Hi
 
I am also interesting to this question and facing this problem to generate the report!
 
Do any 1 have the solution?
 
Thank
 
Bryant
GeneralDB problem perform operationmember__Shah__22 Mar '06 - 0:51 
i want to perform operation Such as Insert,Delete,Edit records in DB.
how to perform.
Generaldid you actually make marks on papermemberbquick15 Mar '06 - 1:38 
nice implementation until i actually clicked the printer icon...
add this routine to restart the printing from the preview form otherwise, it trys to print from beyond the recordset
 
Private Sub prnDoc_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles prnDoc.BeginPrint
InitPrint()
End Sub

Generalexport function to wordmemberwooohoo10 Jan '06 - 5:28 
Can the report exported to word. It will make the report generator complete and editable
 
wooohoo
GeneralReport will not Print (Error)membervb_dot_net26 Dec '05 - 9:12 
All I get when I try to print the Dynamic Report is
A message box saying:
"Please send error message to me for better program,Thank you :There is no row at position 77."
 
Any help please!
 
Thanks
Stan
VB_Dot_Net@msn.com

 
vb_dot_net
 

-- modified at 15:15 Monday 26th December, 2005
GeneralRe: Report will not Print (Error)memberanishmm30 Jan '06 - 17:59 
Helo,
This not a problem
 
This is a little mistake
Don’t worry
 
Please add this three line in your prnDoc_PrintPage()
 

1 PageNumber = 0
2 SumList.Clear()
3 dbCursor = 0L
 

Good luck
anish mm
 

 

 

GeneralRe: Report will not Print (Error)memberPakorn Indhatep4 Feb '06 - 5:05 
Smile | :) Thank you very much. I will fix it.
GeneralRe: Report will not Print (Error)membershigeeru26 Feb '06 - 11:24 
hello,
 
thx for sharing this project. It's great!
However, when i put these three lines in the code, it works fine if you don't change the format of the page. When you change the format from A4 to A4 rotated, something weird happens. I don't know if you encountered the same problem.
 
But the rest works real nice. Nice work...
 
greetz
shigeeru
GeneralColumn summemberRichard Elias19 Nov '05 - 5:20 
If you move the colcount one end if up, this should do the trick.

'------------------ sum ---------------------
If dbSet.Tables(0).Rows(dbCursor)(i + C_has_sumarize) = "Y" Then
SumList(ColCount) += PrintObject
End If
'------------------ end sum -----------------
 
End If
ColCount += 1
Next i
Next j

 
Richard
GeneralRe: Column summemberPakorn Indhatep23 Nov '05 - 22:06 
Thank you very much for your suggestion. I will correct it and upload to code project now. Blush | :O I'm sorry for my bug.
Generalsum (data)memberMarc-André Parizeau14 Oct '05 - 2:33 
Hi, Smile | :)
 
First of all great work... the thing works fine but with one minor flaw. When I am trying to have 2 columns sumurized, it will give me the totals, but both will have the same results.
 
What do I do to arrange this.
 
EXAMPLE:
 
column 1 sum should be = 200.00 and it gives me a result of 200.00
column 2 sum should be = 20.00 BUT gives me a result of 200.00
 
it's like there's only one possibility for
'Has summarize in this column (Y/N)' feature
 
Marc-André Parizeau
GeneralRe: sum (data)memberPakorn Indhatep23 Nov '05 - 22:07 
Thank you very much for your suggestion. I will correct it and upload to code project now. Blush | :O I'm very sorry for my bug.
GeneralDetail explainationmembermansii12 Oct '05 - 20:01 
Dear Pakorn,
I am interested in your Dynamic Report project. I tried it but could not get the data query result in PrintPreview. Yes, the Table's Headers is visible (and looks so nice too).
Could you please show me the way how to do that. Confused | :confused:

 
Regards,
mansii
GeneralRe: Detail explainationmemberPakorn Indhatep14 Oct '05 - 4:30 
Thank you for your interestingSmile | :)
Please copy your query to it or send to my mail(pakorncs@yahoo.com or pakorncs@bizslash.com).If it's possible, please send your table structure (maybe create table statement) to me too. I will check them.
GeneralRe: Detail explainationmembermansii17 Oct '05 - 22:33 
Thank's for your prompt reply, Pakorn.
 
Actually, I haven't made any changes to the project.
I was curious, then I put the query result recordcount to msgbox:
 
MsgBox(frmDynamicPrint.dbSet.Tables(0).Rows.Count)
 
which gives me the correct result (77 rows).
Am I missing something here?
 
Thank's a lot.

 
Regards,
mansii
GeneralRe: (No) Detail Rows? explainationmemberadhsys23 Nov '05 - 11:59 
Yes, I get the same problem.
Only the Wrap Text sample list the data rows. (??)Frown | :(
Please your solution.
Thanks
ADH
GeneralRe: (No) Detail Rows? explainationmemberPakorn Indhatep23 Nov '05 - 22:03 
I'm very sorry. I have a big bug in my code. And the code was put on web It's not complete. Now I copy my code to code project.
GeneralRe: (No) Detail Rows? explanation (OK)memberadhsys24 Nov '05 - 0:44 
Thanks for the great job and the prompt answer and correction.
ADHBig Grin | :-D
GeneralRe: (No) Detail Rows? explainationmembermansii24 Nov '05 - 0:53 
Great, Pakorn!
 
Works like a charm. But, please allow me to help you catching the bugs. It's based on nothing than a salute for you.
 
Here they are:
1. Button "use like component". At the very first action, it shows an err msg, saying "there's no row at position 71" when I click "print" on the report viewer. It doesn't come up on later clicks.
 
2. The "page 1" header doesn't change to actual page number.
 
3. It's not really a bug, but the print button should print "All pages" as stated in Print setup dialog box, not only the active page.
 
I would be very happy if you could fix the bugs asap. Smile | :)
 
Thank you in advance.
 
Regards,
mansii
GeneralNice Work [Suggestion]memberMuhammad Waqas Butt26 Aug '05 - 0:39 
Nice work Buddy.
 
In your code if data columu text legnth more then data coulumn legnth it overlap to next data colum.
 
I just thought if you add some lable positions and Mulitiline grid support this control is going best.
 
Example (Report Sample)
 
Title (Display only first page)
 
Heading1 Heading2
 
Heading4 Heading3
 

________________________________________________________
Data Column1 Data Column1 Data Column1
________________________________________________________
 
1 khkhkjhkhhkhj khhjhkhkjhj
2 jjljfljfldjgdjfgfddfgdfgdf fdfsdfdsffdf
adshgdkashkdjashkd hjkhkhjkhkk
__________________________________________________________
 
Report Summary (Last Page).
 
Muhamad Waqas Butt
waqasb4all@yahoo.com
 
-- modified at 6:51 Friday 26th August, 2005
GeneralRe: Nice Work [Suggestion]memberVertyg027 Aug '05 - 7:46 
Also there could be something like print preview Wink | ;) since i dont have printer.
GeneralThank youmemberPakorn Indhatep27 Aug '05 - 9:37 
Thank you to everybody. Actually, overlap problem is important. I will find the way to correct it. And add the features too. Smile | :)
GeneralRe: Thank youmemberVertyg029 Aug '05 - 2:29 
You just need CanGrow option so that insted of overlaping it breaks into the next column or cut the rest of text off.
Generalversion 1.1memberPakorn Indhatep11 Sep '05 - 22:35 
I updated by your suggestion.
I use start-end positions instead of one definded position.
I will implement wrap text feature later. Smile | :)
Thank you very much.
GeneralRe: version 1.1memberMuhammad Waqas Butt12 Sep '05 - 4:39 
Thanks for reading my suggestions. Please when ever you do it send me must.
 
Best Regard,
 
|Muhamad Waqas Butt|
waqasb4all@yahoo.com
www.sktech.freewebspace.com
 

Generalversion 1.1.1memberPakorn Indhatep13 Sep '05 - 0:34 
Add feature multiple lines and hight of each line. It can use likes the wrap text feature too. Smile | :)
GeneralRe: version 1.1.1memberMuhammad Waqas Butt21 Sep '05 - 5:23 
Thanks for updating the code but may be you not getting my point. I mean this:
 
Column 1 Column2
________________________________
 
Dummy ID1 Dummy Data Line 1
 
Line2 of Column2
Dummy ID2 Dummy Data Line 1
 
Line2 of Column2
___________________________________
 
Exp
 
ID Name & Other
=======================================
1 Muhammmad Waqas Butt
From Pakistan
2 Muhammmad Sheraz Butt
From Pakistan
=======================================
 
May be now my point clear to you.
Please tell if you able to do this.
 
|Muhamad Waqas Butt|
waqasb4all@yahoo.com
www.sktech.freewebspace.com
GeneralRe: version 1.1.1memberPakorn Indhatep21 Sep '05 - 19:28 
Thank you for your answer.
Now,I don't know the solution for get text lenght of the string that write on the printDocument component. If I can get text lenght. I can compare with column lenght and can manage it for wrap text feature like you said. But for new updated, it has 'Change Line Hight' feature. Please try it by button 'Direct Print - Change Line Hight', try change line hight and look at product name column. It work like wrap text feature.
Thank you again for your interesting. I will find the solution for the feature that better than this latest version. Laugh | :laugh:
 

-- modified at 1:29 Thursday 22nd September, 2005
GeneralVersion 1.2 Add wrap text featurememberPakorn Indhatep4 Oct '05 - 18:28 
Already,I added wrap text feature. You can look in the example. Smile | :)
After that, maybe I will add export feature or HTML report by query.
Thank you for your suggestion and interesting.Big Grin | :-D
QuestionSome Questionsmember| Muhammad Waqas Butt |5 Oct '05 - 5:06 
Hello,
How are you? I have seen you artical and i really like you wrap text feature. Can your report code produce this kind of report
 
Sample Report Feature
=====================
 
Report Header 1 Report Header 2
 
Page Header 1 Page Header 1
 
Detail Report (Which contain datagrid)
----------------------------------------
Column1 Column2
----------------------------------------
hkajhskdjhad dgaskdgasjgdasjhdhasjgjdd
dashdhaskdjashdkasjhhd
hkajhskdjhad dgaskdgasjgdasjhdhasjgjdd
dashdhaskdjashdkasjhhd
----------------------------------------
Page Footer 1 Page Footer
 
Report Footer 1 Report Footer 2
=======================================
As in Crystal Report.
Please help me in it.
 
|Muhamad Waqas Butt|
waqasb4all@yahoo.com
www.sktech.freewebspace.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 24 Nov 2005
Article Copyright 2005 by Pakorn Indhatep
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid