Click here to Skip to main content
13,595,433 members
Click here to Skip to main content
Articles » Multimedia » GDI+ » General » Downloads

Stats

27.7K views
1.2K downloads
39 bookmarked
Posted 29 Dec 2012
Licenced CPOL

WPF-Less GDI+.NET Report Component: Star Report

, 25 Jan 2013
StarReport: WPF-less GDI+.NET report component.
UniverseReportDemo
UniverseReport_WithoutPrinter_Project
UniverseReport
mac_button.png
mac_checkbox.png
mac_radiobutton.png
Plex_button.png
Plex_checkbox.png
Plex_radiobutton.png
Properties
Resources
Report1.bmp
StarReport.png
Thumbs.db
UniverseReport.csproj.user
UniverseReport.suo
UpgradeLog.XML
xp1_button.png
xp1_checkbox.png
xp1_radiobutton.png
UniverseReportDemo.suo
UniverseReportDemo
bin
Debug
Properties
mac_button.png
mac_checkbox.png
mac_radiobutton.png
Plex_button.png
Plex_checkbox.png
Plex_radiobutton.png
Report1.bmp
StarReport.png
Thumbs.db
UniverseReport.csproj.user
UniverseReport.suo
UpgradeLog.XML
xp1_button.png
xp1_checkbox.png
xp1_radiobutton.png
UniverseReportDemo.suo
UniverseReport.dll
#region Using
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

using System.ComponentModel;
using System.ComponentModel.Design;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Resources;

using System.Text;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Drawing.Text;

using System.Runtime.Serialization;
using System.ComponentModel.Design.Serialization;

using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;

#endregion

namespace UniverseReport
{
    [Designer(typeof(StarReportDesigner))]
    [Serializable()]
    [ToolboxBitmap(typeof(StarReport), "StarReport.png")]
    public class StarReport : System.Windows.Forms.UserControl
    {
        private System.ComponentModel.IContainer components;

        bool hasMorePages = true;
        int marginBounds_Left = 48;
        int marginBounds_Width = 720;
        int marginBounds_Right = 768;
        int marginBounds_Top = 48;
        int marginBounds_Bottom = 1008;
        int marginBounds_Height = 960;
        int marginBounds_X = 48;
        int marginBounds_Y = 49;
        int pageBounds_Width = 816;
        int pageBounds_Height = 1056;
        int leftMargin = 48;



        #region Declarations
        private ThemedButton btnNextPage;
        private ThemedButton btnPreviousPage;
        private ThemedButton btnFirst;
        private ThemedButton btnLast;
        private ThemedButton btnZoomIn;
        private ThemedButton btnZoomOut;
        private ThemedButton btnFilter;
        private ThemedButton btnPrint;


        private System.Windows.Forms.Button btnSample;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.StatusBar sb;
        private System.Windows.Forms.StatusBarPanel sbpCurrentPage;
        private System.Windows.Forms.StatusBarPanel sbpTotalPages;
        private System.Windows.Forms.StatusBarPanel sbpZoomFactor;
        private System.Windows.Forms.ToolTip tt;

        private System.Windows.Forms.Panel pnlPage;
        private System.Windows.Forms.GroupBox grmMain;
        private System.Windows.Forms.NumericUpDown neColumns;
        private System.Windows.Forms.NumericUpDown neRows;
        private System.Windows.Forms.ComboBox cbxZoom;
        private System.Windows.Forms.NumericUpDown nePages;
        private Label label1;
        private Label label4;
        private Label label3;
        private Label label2;
        private ContextMenuStrip cmStrip;
        private ToolStripMenuItem mnNextPage;
        private ToolStripMenuItem mnPreviousPage;
        private ToolStripMenuItem mnPrint;
        private ToolStripMenuItem mnFilter;
        private ToolStripMenuItem mnZoom;
        private ToolStripMenuItem mnAuto;
        private ToolStripMenuItem mn500;
        private ToolStripMenuItem mn200;
        private ToolStripMenuItem mn150;
        private ToolStripMenuItem mn100;
        private ToolStripMenuItem mn90;
        private ToolStripMenuItem mn80;
        private ToolStripMenuItem mn75;
        private ToolStripMenuItem mn70;
        private ToolStripMenuItem mnMultiplePages;
        private ToolStripMenuItem mn60;
        private ToolStripMenuItem mn50;
        private ToolStripMenuItem mn40;
        private ToolStripMenuItem mn30;
        private ToolStripMenuItem mn1x1;
        private ToolStripMenuItem mn1x2;
        private ToolStripMenuItem mn1x3;
        private ToolStripMenuItem mn2x1;
        private ToolStripMenuItem mn2x2;
        private ToolStripMenuItem mn2x3;
        private PrintPreviewControl pp;

        #endregion

        #region My Declarations

        string deltaText = String.Empty;
        string deltaText2 = String.Empty;


        private frmFilter filter = new frmFilter();

        //Initialize dummy rect for drawing text
        Rectangle rect = new Rectangle(0, 0, 0, 0);

        private PrintDocument document = new PrintDocument();
        private PrintPreviewDialog printPreview = new PrintPreviewDialog();
        private PrinterSettings printerSettings = new PrinterSettings();
        private PageSettings pageSettings = new PageSettings();


        private DataTable currentTable = null;

        private StringFormat defaultStringFormat = new StringFormat();

        private int currentPage = 1;
        private int numPages = 1;

        private string reportName = String.Empty;
        private Report report = new Report();
        private const float CENTIMETER_TO_INCH = 0.3937f;


        //used to keep track of the current DataRow in the currentData table
        int recordIndex = 0;
        private int x = 8;


        SolidBrush myBrush;
        private Button btnTablePicker;
        private Display display;
        private PictureBox pictureBox1;
        private PictureBox pictureBox2;
        private PictureBox pictureBox3;
        private PictureBox pictureBox4;
        private PictureBox pictureBox5;
        private ThemedButton btnPrintPreview;
        Pen linePen;

        #endregion

        #region Constructor Etc
        public StarReport()
        {
            // This call is required by the Windows.Forms Form Designer.
            InitializeComponent();
            Init();
            // TODO: Add any initialization after the InitializeComponent call

        }

        #region Component Designer generated code
        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(StarReport));
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.display = new UniverseReport.Display();
            this.pnlPage = new System.Windows.Forms.Panel();
            this.btnSample = new System.Windows.Forms.Button();
            this.pp = new System.Windows.Forms.PrintPreviewControl();
            this.cmStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.mnNextPage = new System.Windows.Forms.ToolStripMenuItem();
            this.mnPreviousPage = new System.Windows.Forms.ToolStripMenuItem();
            this.mnPrint = new System.Windows.Forms.ToolStripMenuItem();
            this.mnFilter = new System.Windows.Forms.ToolStripMenuItem();
            this.mnZoom = new System.Windows.Forms.ToolStripMenuItem();
            this.mnAuto = new System.Windows.Forms.ToolStripMenuItem();
            this.mn500 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn200 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn150 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn100 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn90 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn80 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn75 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn70 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn60 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn50 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn40 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn30 = new System.Windows.Forms.ToolStripMenuItem();
            this.mnMultiplePages = new System.Windows.Forms.ToolStripMenuItem();
            this.mn1x1 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn1x2 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn1x3 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn2x1 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn2x2 = new System.Windows.Forms.ToolStripMenuItem();
            this.mn2x3 = new System.Windows.Forms.ToolStripMenuItem();
            this.sb = new System.Windows.Forms.StatusBar();
            this.sbpCurrentPage = new System.Windows.Forms.StatusBarPanel();
            this.sbpTotalPages = new System.Windows.Forms.StatusBarPanel();
            this.sbpZoomFactor = new System.Windows.Forms.StatusBarPanel();
            this.tt = new System.Windows.Forms.ToolTip(this.components);
            this.btnTablePicker = new System.Windows.Forms.Button();
            this.btnPrintPreview = new UniverseReport.ThemedButton();
            this.btnNextPage = new UniverseReport.ThemedButton();
            this.btnPreviousPage = new UniverseReport.ThemedButton();
            this.btnFirst = new UniverseReport.ThemedButton();
            this.btnLast = new UniverseReport.ThemedButton();
            this.btnZoomIn = new UniverseReport.ThemedButton();
            this.btnZoomOut = new UniverseReport.ThemedButton();
            this.btnFilter = new UniverseReport.ThemedButton();
            this.btnPrint = new UniverseReport.ThemedButton();
            this.grmMain = new System.Windows.Forms.GroupBox();
            this.nePages = new System.Windows.Forms.NumericUpDown();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.neColumns = new System.Windows.Forms.NumericUpDown();
            this.neRows = new System.Windows.Forms.NumericUpDown();
            this.cbxZoom = new System.Windows.Forms.ComboBox();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.pictureBox2 = new System.Windows.Forms.PictureBox();
            this.pictureBox3 = new System.Windows.Forms.PictureBox();
            this.pictureBox4 = new System.Windows.Forms.PictureBox();
            this.pictureBox5 = new System.Windows.Forms.PictureBox();
            this.groupBox2.SuspendLayout();
            this.pnlPage.SuspendLayout();
            this.cmStrip.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.sbpCurrentPage)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpTotalPages)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpZoomFactor)).BeginInit();
            this.grmMain.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nePages)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.neColumns)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.neRows)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit();
            this.SuspendLayout();
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.display);
            this.groupBox2.Controls.Add(this.pnlPage);
            this.groupBox2.Controls.Add(this.pp);
            this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
            this.groupBox2.Location = new System.Drawing.Point(0, 59);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(616, 319);
            this.groupBox2.TabIndex = 9;
            this.groupBox2.TabStop = false;
            // 
            // display
            // 
            this.display.BackColor = System.Drawing.Color.White;
            this.display.Dock = System.Windows.Forms.DockStyle.Fill;
            this.display.Location = new System.Drawing.Point(115, 17);
            this.display.Name = "display";
            this.display.Size = new System.Drawing.Size(498, 299);
            this.display.TabIndex = 1;
            // 
            // pnlPage
            // 
            this.pnlPage.AutoScroll = true;
            this.pnlPage.BackColor = System.Drawing.SystemColors.Control;
            this.pnlPage.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.pnlPage.Controls.Add(this.btnSample);
            this.pnlPage.Dock = System.Windows.Forms.DockStyle.Left;
            this.pnlPage.Location = new System.Drawing.Point(3, 17);
            this.pnlPage.Name = "pnlPage";
            this.pnlPage.Size = new System.Drawing.Size(112, 299);
            this.pnlPage.TabIndex = 1;
            this.tt.SetToolTip(this.pnlPage, "Pages Tab");
            this.pnlPage.Click += new System.EventHandler(this.pnlPage_Click);
            // 
            // btnSample
            // 
            this.btnSample.BackColor = System.Drawing.Color.White;
            this.btnSample.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnSample.Font = new System.Drawing.Font("Tahoma", 6F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnSample.Image = global::UniverseReport.Properties.Resources.Report;
            this.btnSample.Location = new System.Drawing.Point(6, 8);
            this.btnSample.Name = "btnSample";
            this.btnSample.Size = new System.Drawing.Size(63, 72);
            this.btnSample.TabIndex = 0;
            this.btnSample.Text = "Page 1";
            this.btnSample.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            this.btnSample.TextImageRelation = System.Windows.Forms.TextImageRelation.TextAboveImage;
            this.tt.SetToolTip(this.btnSample, "Page 1");
            this.btnSample.UseVisualStyleBackColor = false;
            this.btnSample.Visible = false;
            // 
            // pp
            // 
            this.pp.BackColor = System.Drawing.Color.White;
            this.pp.ContextMenuStrip = this.cmStrip;
            this.pp.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pp.Location = new System.Drawing.Point(3, 17);
            this.pp.Name = "pp";
            this.pp.Size = new System.Drawing.Size(610, 299);
            this.pp.TabIndex = 2;
            this.pp.Visible = false;
            // 
            // cmStrip
            // 
            this.cmStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.mnNextPage,
            this.mnPreviousPage,
            this.mnPrint,
            this.mnFilter,
            this.mnZoom,
            this.mnMultiplePages});
            this.cmStrip.Name = "cmStrip";
            this.cmStrip.Size = new System.Drawing.Size(158, 136);
            this.cmStrip.Opening += new System.ComponentModel.CancelEventHandler(this.cmStrip_Opening);
            this.cmStrip.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.cmStrip_ItemClicked);
            // 
            // mnNextPage
            // 
            this.mnNextPage.Image = ((System.Drawing.Image)(resources.GetObject("mnNextPage.Image")));
            this.mnNextPage.Name = "mnNextPage";
            this.mnNextPage.Size = new System.Drawing.Size(157, 22);
            this.mnNextPage.Text = "Next Page";
            // 
            // mnPreviousPage
            // 
            this.mnPreviousPage.Image = ((System.Drawing.Image)(resources.GetObject("mnPreviousPage.Image")));
            this.mnPreviousPage.Name = "mnPreviousPage";
            this.mnPreviousPage.Size = new System.Drawing.Size(157, 22);
            this.mnPreviousPage.Text = "Previous Page";
            // 
            // mnPrint
            // 
            this.mnPrint.Image = ((System.Drawing.Image)(resources.GetObject("mnPrint.Image")));
            this.mnPrint.Name = "mnPrint";
            this.mnPrint.Size = new System.Drawing.Size(157, 22);
            this.mnPrint.Text = "Print...";
            // 
            // mnFilter
            // 
            this.mnFilter.Image = ((System.Drawing.Image)(resources.GetObject("mnFilter.Image")));
            this.mnFilter.Name = "mnFilter";
            this.mnFilter.Size = new System.Drawing.Size(157, 22);
            this.mnFilter.Text = "Filter Report...";
            // 
            // mnZoom
            // 
            this.mnZoom.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.mnAuto,
            this.mn500,
            this.mn200,
            this.mn150,
            this.mn100,
            this.mn90,
            this.mn80,
            this.mn75,
            this.mn70,
            this.mn60,
            this.mn50,
            this.mn40,
            this.mn30});
            this.mnZoom.Image = ((System.Drawing.Image)(resources.GetObject("mnZoom.Image")));
            this.mnZoom.Name = "mnZoom";
            this.mnZoom.Size = new System.Drawing.Size(157, 22);
            this.mnZoom.Text = "Zoom";
            // 
            // mnAuto
            // 
            this.mnAuto.Name = "mnAuto";
            this.mnAuto.Size = new System.Drawing.Size(114, 22);
            this.mnAuto.Text = "Auto";
            this.mnAuto.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn500
            // 
            this.mn500.Name = "mn500";
            this.mn500.Size = new System.Drawing.Size(114, 22);
            this.mn500.Text = "500%";
            this.mn500.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn200
            // 
            this.mn200.Name = "mn200";
            this.mn200.Size = new System.Drawing.Size(114, 22);
            this.mn200.Text = "200%";
            this.mn200.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn150
            // 
            this.mn150.Name = "mn150";
            this.mn150.Size = new System.Drawing.Size(114, 22);
            this.mn150.Text = "150%";
            this.mn150.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn100
            // 
            this.mn100.Name = "mn100";
            this.mn100.Size = new System.Drawing.Size(114, 22);
            this.mn100.Text = "100%";
            this.mn100.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn90
            // 
            this.mn90.Name = "mn90";
            this.mn90.Size = new System.Drawing.Size(114, 22);
            this.mn90.Text = "  90%";
            this.mn90.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn80
            // 
            this.mn80.Name = "mn80";
            this.mn80.Size = new System.Drawing.Size(114, 22);
            this.mn80.Text = "  80%";
            this.mn80.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn75
            // 
            this.mn75.Name = "mn75";
            this.mn75.Size = new System.Drawing.Size(114, 22);
            this.mn75.Text = "  75%";
            this.mn75.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn70
            // 
            this.mn70.Name = "mn70";
            this.mn70.Size = new System.Drawing.Size(114, 22);
            this.mn70.Text = "  70%";
            this.mn70.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn60
            // 
            this.mn60.Name = "mn60";
            this.mn60.Size = new System.Drawing.Size(114, 22);
            this.mn60.Text = "  60%";
            this.mn60.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn50
            // 
            this.mn50.Name = "mn50";
            this.mn50.Size = new System.Drawing.Size(114, 22);
            this.mn50.Text = "  50%";
            this.mn50.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn40
            // 
            this.mn40.Name = "mn40";
            this.mn40.Size = new System.Drawing.Size(114, 22);
            this.mn40.Text = "  40%";
            this.mn40.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mn30
            // 
            this.mn30.Name = "mn30";
            this.mn30.Size = new System.Drawing.Size(114, 22);
            this.mn30.Text = "  30%";
            this.mn30.Click += new System.EventHandler(this.ZoomItemsClicked);
            // 
            // mnMultiplePages
            // 
            this.mnMultiplePages.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.mn1x1,
            this.mn1x2,
            this.mn1x3,
            this.mn2x1,
            this.mn2x2,
            this.mn2x3});
            this.mnMultiplePages.Image = ((System.Drawing.Image)(resources.GetObject("mnMultiplePages.Image")));
            this.mnMultiplePages.Name = "mnMultiplePages";
            this.mnMultiplePages.Size = new System.Drawing.Size(157, 22);
            this.mnMultiplePages.Text = "Multiple Pages";
            // 
            // mn1x1
            // 
            this.mn1x1.Name = "mn1x1";
            this.mn1x1.Size = new System.Drawing.Size(109, 22);
            this.mn1x1.Text = "1 x 1";
            this.mn1x1.Click += new System.EventHandler(this.MultiplyItemsClicked);
            // 
            // mn1x2
            // 
            this.mn1x2.Name = "mn1x2";
            this.mn1x2.Size = new System.Drawing.Size(109, 22);
            this.mn1x2.Text = "1 x 2";
            this.mn1x2.Click += new System.EventHandler(this.MultiplyItemsClicked);
            // 
            // mn1x3
            // 
            this.mn1x3.Name = "mn1x3";
            this.mn1x3.Size = new System.Drawing.Size(109, 22);
            this.mn1x3.Text = "1 x 3";
            this.mn1x3.Click += new System.EventHandler(this.MultiplyItemsClicked);
            // 
            // mn2x1
            // 
            this.mn2x1.Name = "mn2x1";
            this.mn2x1.Size = new System.Drawing.Size(109, 22);
            this.mn2x1.Text = "2 x 1";
            this.mn2x1.Click += new System.EventHandler(this.MultiplyItemsClicked);
            // 
            // mn2x2
            // 
            this.mn2x2.Name = "mn2x2";
            this.mn2x2.Size = new System.Drawing.Size(109, 22);
            this.mn2x2.Text = "2 x 2";
            this.mn2x2.Click += new System.EventHandler(this.MultiplyItemsClicked);
            // 
            // mn2x3
            // 
            this.mn2x3.Name = "mn2x3";
            this.mn2x3.Size = new System.Drawing.Size(109, 22);
            this.mn2x3.Text = "2 x 3";
            this.mn2x3.Click += new System.EventHandler(this.MultiplyItemsClicked);
            // 
            // sb
            // 
            this.sb.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.sb.Location = new System.Drawing.Point(0, 378);
            this.sb.Name = "sb";
            this.sb.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
            this.sbpCurrentPage,
            this.sbpTotalPages,
            this.sbpZoomFactor});
            this.sb.ShowPanels = true;
            this.sb.Size = new System.Drawing.Size(616, 22);
            this.sb.SizingGrip = false;
            this.sb.TabIndex = 10;
            // 
            // sbpCurrentPage
            // 
            this.sbpCurrentPage.Icon = ((System.Drawing.Icon)(resources.GetObject("sbpCurrentPage.Icon")));
            this.sbpCurrentPage.Name = "sbpCurrentPage";
            this.sbpCurrentPage.Text = "Current Page No.:";
            this.sbpCurrentPage.ToolTipText = "The current page number";
            this.sbpCurrentPage.Width = 170;
            // 
            // sbpTotalPages
            // 
            this.sbpTotalPages.Icon = ((System.Drawing.Icon)(resources.GetObject("sbpTotalPages.Icon")));
            this.sbpTotalPages.Name = "sbpTotalPages";
            this.sbpTotalPages.Text = "Total Pages:";
            this.sbpTotalPages.Width = 120;
            // 
            // sbpZoomFactor
            // 
            this.sbpZoomFactor.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
            this.sbpZoomFactor.Icon = ((System.Drawing.Icon)(resources.GetObject("sbpZoomFactor.Icon")));
            this.sbpZoomFactor.Name = "sbpZoomFactor";
            this.sbpZoomFactor.Text = "Zoom Factor:";
            this.sbpZoomFactor.Width = 326;
            // 
            // tt
            // 
            this.tt.IsBalloon = true;
            // 
            // btnTablePicker
            // 
            this.btnTablePicker.Location = new System.Drawing.Point(128, 43);
            this.btnTablePicker.Name = "btnTablePicker";
            this.btnTablePicker.Size = new System.Drawing.Size(104, 10);
            this.btnTablePicker.TabIndex = 35;
            this.tt.SetToolTip(this.btnTablePicker, "Select Rows and Columns");
            this.btnTablePicker.UseVisualStyleBackColor = true;
            this.btnTablePicker.Visible = false;
            this.btnTablePicker.Click += new System.EventHandler(this.btnTablePicker_Click);
            // 
            // btnPrintPreview
            // 
            this.btnPrintPreview.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnPrintPreview.Image = ((System.Drawing.Image)(resources.GetObject("btnPrintPreview.Image")));
            this.btnPrintPreview.Location = new System.Drawing.Point(550, 16);
            this.btnPrintPreview.Name = "btnPrintPreview";
            this.btnPrintPreview.Size = new System.Drawing.Size(25, 25);
            this.btnPrintPreview.TabIndex = 37;
            this.tt.SetToolTip(this.btnPrintPreview, "Preview Report");
            this.btnPrintPreview.UseVisualStyleBackColor = true;
            this.btnPrintPreview.Click += new System.EventHandler(this.btnPrintPreview_Click);
            // 
            // btnNextPage
            // 
            this.btnNextPage.Image = ((System.Drawing.Image)(resources.GetObject("btnNextPage.Image")));
            this.btnNextPage.Location = new System.Drawing.Point(302, 16);
            this.btnNextPage.Name = "btnNextPage";
            this.btnNextPage.Size = new System.Drawing.Size(25, 25);
            this.btnNextPage.TabIndex = 3;
            this.tt.SetToolTip(this.btnNextPage, "Go to Next Page");
            this.btnNextPage.UseVisualStyleBackColor = true;
            this.btnNextPage.Click += new System.EventHandler(this.btnNextPage_Click);
            // 
            // btnPreviousPage
            // 
            this.btnPreviousPage.Image = ((System.Drawing.Image)(resources.GetObject("btnPreviousPage.Image")));
            this.btnPreviousPage.Location = new System.Drawing.Point(278, 16);
            this.btnPreviousPage.Name = "btnPreviousPage";
            this.btnPreviousPage.Size = new System.Drawing.Size(25, 25);
            this.btnPreviousPage.TabIndex = 3;
            this.tt.SetToolTip(this.btnPreviousPage, "Go to Previous Page");
            this.btnPreviousPage.UseVisualStyleBackColor = true;
            this.btnPreviousPage.Click += new System.EventHandler(this.btnPreviousPage_Click);
            // 
            // btnFirst
            // 
            this.btnFirst.Image = ((System.Drawing.Image)(resources.GetObject("btnFirst.Image")));
            this.btnFirst.Location = new System.Drawing.Point(253, 16);
            this.btnFirst.Name = "btnFirst";
            this.btnFirst.Size = new System.Drawing.Size(25, 25);
            this.btnFirst.TabIndex = 3;
            this.tt.SetToolTip(this.btnFirst, "Go to First Page");
            this.btnFirst.UseVisualStyleBackColor = true;
            this.btnFirst.Click += new System.EventHandler(this.btnTFirst_Click);
            // 
            // btnLast
            // 
            this.btnLast.Image = ((System.Drawing.Image)(resources.GetObject("btnLast.Image")));
            this.btnLast.Location = new System.Drawing.Point(326, 16);
            this.btnLast.Name = "btnLast";
            this.btnLast.Size = new System.Drawing.Size(25, 25);
            this.btnLast.TabIndex = 31;
            this.tt.SetToolTip(this.btnLast, "Go to Last Page");
            this.btnLast.UseVisualStyleBackColor = true;
            this.btnLast.Click += new System.EventHandler(this.btnTLast_Click);
            // 
            // btnZoomIn
            // 
            this.btnZoomIn.Image = ((System.Drawing.Image)(resources.GetObject("btnZoomIn.Image")));
            this.btnZoomIn.Location = new System.Drawing.Point(375, 16);
            this.btnZoomIn.Name = "btnZoomIn";
            this.btnZoomIn.Size = new System.Drawing.Size(25, 25);
            this.btnZoomIn.TabIndex = 30;
            this.tt.SetToolTip(this.btnZoomIn, "Zoom In");
            this.btnZoomIn.UseVisualStyleBackColor = true;
            this.btnZoomIn.Visible = false;
            this.btnZoomIn.Click += new System.EventHandler(this.btnZoomIn_Click);
            // 
            // btnZoomOut
            // 
            this.btnZoomOut.Image = ((System.Drawing.Image)(resources.GetObject("btnZoomOut.Image")));
            this.btnZoomOut.Location = new System.Drawing.Point(400, 16);
            this.btnZoomOut.Name = "btnZoomOut";
            this.btnZoomOut.Size = new System.Drawing.Size(25, 25);
            this.btnZoomOut.TabIndex = 29;
            this.tt.SetToolTip(this.btnZoomOut, "Zoom Out");
            this.btnZoomOut.UseVisualStyleBackColor = true;
            this.btnZoomOut.Visible = false;
            this.btnZoomOut.Click += new System.EventHandler(this.btnZoomOut_Click);
            // 
            // btnFilter
            // 
            this.btnFilter.Image = ((System.Drawing.Image)(resources.GetObject("btnFilter.Image")));
            this.btnFilter.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
            this.btnFilter.Location = new System.Drawing.Point(440, 16);
            this.btnFilter.Name = "btnFilter";
            this.btnFilter.Size = new System.Drawing.Size(101, 25);
            this.btnFilter.TabIndex = 28;
            this.btnFilter.Text = "Filter Table";
            this.tt.SetToolTip(this.btnFilter, "Filter Records in table");
            this.btnFilter.UseVisualStyleBackColor = true;
            this.btnFilter.Click += new System.EventHandler(this.btnFilter_Click);
            // 
            // btnPrint
            // 
            this.btnPrint.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnPrint.Image = ((System.Drawing.Image)(resources.GetObject("btnPrint.Image")));
            this.btnPrint.Location = new System.Drawing.Point(576, 16);
            this.btnPrint.Name = "btnPrint";
            this.btnPrint.Size = new System.Drawing.Size(25, 25);
            this.btnPrint.TabIndex = 27;
            this.tt.SetToolTip(this.btnPrint, "Print Report");
            this.btnPrint.UseVisualStyleBackColor = true;
            this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
            // 
            // grmMain
            // 
            this.grmMain.Controls.Add(this.nePages);
            this.grmMain.Controls.Add(this.btnPrintPreview);
            this.grmMain.Controls.Add(this.btnTablePicker);
            this.grmMain.Controls.Add(this.label4);
            this.grmMain.Controls.Add(this.label3);
            this.grmMain.Controls.Add(this.label2);
            this.grmMain.Controls.Add(this.label1);
            this.grmMain.Controls.Add(this.btnNextPage);
            this.grmMain.Controls.Add(this.btnPreviousPage);
            this.grmMain.Controls.Add(this.btnFirst);
            this.grmMain.Controls.Add(this.btnLast);
            this.grmMain.Controls.Add(this.btnZoomIn);
            this.grmMain.Controls.Add(this.btnZoomOut);
            this.grmMain.Controls.Add(this.btnFilter);
            this.grmMain.Controls.Add(this.btnPrint);
            this.grmMain.Controls.Add(this.neColumns);
            this.grmMain.Controls.Add(this.neRows);
            this.grmMain.Controls.Add(this.cbxZoom);
            this.grmMain.Dock = System.Windows.Forms.DockStyle.Top;
            this.grmMain.Location = new System.Drawing.Point(0, 0);
            this.grmMain.Name = "grmMain";
            this.grmMain.Size = new System.Drawing.Size(616, 59);
            this.grmMain.TabIndex = 12;
            this.grmMain.TabStop = false;
            // 
            // nePages
            // 
            this.nePages.Location = new System.Drawing.Point(8, 22);
            this.nePages.Maximum = new decimal(new int[] {
            1000,
            0,
            0,
            0});
            this.nePages.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.nePages.Name = "nePages";
            this.nePages.Size = new System.Drawing.Size(48, 21);
            this.nePages.TabIndex = 20;
            this.nePages.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            this.nePages.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.nePages.ValueChanged += new System.EventHandler(this.nePages_ValueChanged);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.Location = new System.Drawing.Point(188, 9);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(22, 11);
            this.label4.TabIndex = 34;
            this.label4.Text = "Col:";
            this.label4.Visible = false;
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(130, 9);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(27, 11);
            this.label3.TabIndex = 34;
            this.label3.Text = "Row:";
            this.label3.Visible = false;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label2.Location = new System.Drawing.Point(8, 10);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(29, 11);
            this.label2.TabIndex = 33;
            this.label2.Text = "Page:";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Font = new System.Drawing.Font("Tahoma", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label1.Location = new System.Drawing.Point(73, 10);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(31, 11);
            this.label1.TabIndex = 32;
            this.label1.Text = "Zoom:";
            this.label1.Visible = false;
            // 
            // neColumns
            // 
            this.neColumns.Location = new System.Drawing.Point(184, 19);
            this.neColumns.Maximum = new decimal(new int[] {
            1000,
            0,
            0,
            0});
            this.neColumns.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.neColumns.Name = "neColumns";
            this.neColumns.Size = new System.Drawing.Size(48, 21);
            this.neColumns.TabIndex = 21;
            this.neColumns.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            this.neColumns.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.neColumns.Visible = false;
            this.neColumns.ValueChanged += new System.EventHandler(this.neColumns_ValueChanged);
            // 
            // neRows
            // 
            this.neRows.Location = new System.Drawing.Point(128, 19);
            this.neRows.Maximum = new decimal(new int[] {
            1000,
            0,
            0,
            0});
            this.neRows.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.neRows.Name = "neRows";
            this.neRows.Size = new System.Drawing.Size(48, 21);
            this.neRows.TabIndex = 22;
            this.neRows.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
            this.neRows.Value = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.neRows.Visible = false;
            this.neRows.ValueChanged += new System.EventHandler(this.neRows_ValueChanged);
            // 
            // cbxZoom
            // 
            this.cbxZoom.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cbxZoom.Items.AddRange(new object[] {
            "Auto",
            "500%",
            "200%",
            "150%",
            "100%",
            "90%",
            "80%",
            "75%",
            "70%",
            "60%",
            "50%",
            "40%",
            "30%"});
            this.cbxZoom.Location = new System.Drawing.Point(70, 23);
            this.cbxZoom.Name = "cbxZoom";
            this.cbxZoom.Size = new System.Drawing.Size(51, 21);
            this.cbxZoom.TabIndex = 19;
            this.cbxZoom.Visible = false;
            this.cbxZoom.SelectedIndexChanged += new System.EventHandler(this.cbxZoom_SelectedIndexChanged);
            // 
            // pictureBox1
            // 
            this.pictureBox1.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.InitialImage")));
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(100, 50);
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            // 
            // pictureBox2
            // 
            this.pictureBox2.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox2.InitialImage")));
            this.pictureBox2.Location = new System.Drawing.Point(0, 0);
            this.pictureBox2.Name = "pictureBox2";
            this.pictureBox2.Size = new System.Drawing.Size(100, 50);
            this.pictureBox2.TabIndex = 0;
            this.pictureBox2.TabStop = false;
            // 
            // pictureBox3
            // 
            this.pictureBox3.Location = new System.Drawing.Point(0, 0);
            this.pictureBox3.Name = "pictureBox3";
            this.pictureBox3.Size = new System.Drawing.Size(100, 50);
            this.pictureBox3.TabIndex = 0;
            this.pictureBox3.TabStop = false;
            // 
            // pictureBox4
            // 
            this.pictureBox4.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox4.InitialImage")));
            this.pictureBox4.Location = new System.Drawing.Point(0, 0);
            this.pictureBox4.Name = "pictureBox4";
            this.pictureBox4.Size = new System.Drawing.Size(100, 50);
            this.pictureBox4.TabIndex = 0;
            this.pictureBox4.TabStop = false;
            // 
            // pictureBox5
            // 
            this.pictureBox5.InitialImage = ((System.Drawing.Image)(resources.GetObject("pictureBox5.InitialImage")));
            this.pictureBox5.Location = new System.Drawing.Point(0, 0);
            this.pictureBox5.Name = "pictureBox5";
            this.pictureBox5.Size = new System.Drawing.Size(100, 50);
            this.pictureBox5.TabIndex = 0;
            this.pictureBox5.TabStop = false;
            // 
            // StarReport
            // 
            this.BackColor = System.Drawing.Color.White;
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.grmMain);
            this.Controls.Add(this.sb);
            this.DoubleBuffered = true;
            this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Name = "StarReport";
            this.Size = new System.Drawing.Size(616, 400);
            this.Resize += new System.EventHandler(this.StarReport_Resize);
            this.groupBox2.ResumeLayout(false);
            this.pnlPage.ResumeLayout(false);
            this.cmStrip.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.sbpCurrentPage)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpTotalPages)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.sbpZoomFactor)).EndInit();
            this.grmMain.ResumeLayout(false);
            this.grmMain.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.nePages)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.neColumns)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.neRows)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion


        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        #endregion

        #region Init
        public void Init()
        {
            report.Settings = report.Settings;
            // report.Data = report.Data;

            document.PrintPage += new PrintPageEventHandler(PrintPage);
            document.QueryPageSettings += new QueryPageSettingsEventHandler(QueryPageSettings);

            printPreview.Document = document;


            cbxZoom.SelectedIndex = 4;


            report.Settings.MyBrush = new SolidBrush(report.Settings.RowSeparatorLine.Color);

            myBrush = report.Settings.MyBrush;
            report.Settings.LinePen = new Pen(myBrush, (float)report.Settings.RowSeparatorLine.Thickness);
            linePen = report.Settings.LinePen;
        }

        #endregion

        #region Properties
        [Category("Report Data")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public Report Report
        {
            get { return report; }
        }

        [Browsable(false)]
        public DataTable DataTable
        {
            get { return currentTable; }
            set { currentTable = value; }

        }


        [Browsable(false)]
        public PrintPreviewDialog PrintPreviewDialog
        {
            get { return printPreview; }
            set
            {
                printPreview = value;
                printPreview.Document = this.document;
            }
        }


        [Browsable(false)]
        public PrintDocument PrintDocument
        {
            get { return document; }
            set { document = value; }
        }


        [Browsable(false)]
        public PrinterSettings PrinterSettings
        {
            get { return printerSettings; }
            set { printerSettings = value; }
        }

        [Browsable(false)]
        public PageSettings PageSettings
        {
            get { return pageSettings; }
            set { pageSettings = value; }
        }

        [Browsable(false)]
        public PrintPreviewControl PrintPreviewControl
        {
            get { return pp; }
            set { pp = value; }
        }


        #endregion

        #region Procedures


        private void UpdateStatusbar()
        {
            sb.Panels[0].Text = "Current Page No.: " + nePages.Value.ToString();
            sb.Panels[1].Text = "Total Pages: " + numPages.ToString();
            sb.Panels[2].Text = "Zoom Factor: " + cbxZoom.SelectedItem.ToString();
        }

        public bool ShouldSerializePrinterSettings()
        {
            return false;
        }

        public bool ShouldSerializePrintDocument()
        {
            return false;
        }

        public void ShowPreviewDialog()
        {
            if (!PrinterInstalled())
            {

                return;
            }

            printPreview.ShowDialog();
        }


        /// <summary>
        /// Resets all the collections and objects in this report.
        /// Should be called before a creation of each report
        /// </summary>
        public void Reset()
        {
            report.Data.Group.RowCellInfos.Clear();
            report.Data.SubGroup.Columns.Clear();
            report.Data.SubGroup.RowCellInfos.Clear();
            report.Data.SubGroup.SkipPageOnChange = false;
            report.Data.SubGroup2.Columns.Clear();
            report.Data.SubGroup2.RowCellInfos.Clear();
            report.Data.ColumnCellCollection.Clear();
            report.Data.TextSections.Clear();
            report.Data.Lines.Clear();
            report.Data.FreeFormCells.Clear();
            report.Data.Rectangles.Clear();
            report.Data.Images.Clear();

            PageSettings.Landscape = false;
            deltaText = String.Empty;
            deltaText2 = String.Empty;


            //Reset parameters to portrait (not landscape)
             marginBounds_Left = 48;
             marginBounds_Width = 720;
             marginBounds_Right = 768;
             marginBounds_Top = 48;
             marginBounds_Bottom = 1008;
             marginBounds_Height = 960;
             marginBounds_X = 48;
             marginBounds_Y = 49;
             pageBounds_Width = 816;
             pageBounds_Height = 1056;
             leftMargin = 48;





            report.Settings.OutlineTable = true;
            report.Settings.CalculatedField = String.Empty;
            report.Settings.PrintHeading = PrintHeading.OnFirstPage;
            report.Settings.ReportType = ReportType.GeneralList;

            report.Settings.UseTableInFreeForm = false;
            report.Settings.PrintRowSeparator = true;
            report.Settings.ReportDate = PrintReportDateLocation.RightTop;
            defaultStringFormat = new StringFormat();
            report.Settings.PrintPageNumbers = true;

            report.Settings.SumText = "Total:";
            report.Settings.AverageText = "Average:";
            report.Settings.CountText = "Count:";
            report.Settings.MaximumText = "Max:";
            report.Settings.MinimumText = "Min:";

            if (filter != null)
                filter.ClearFilters();

            report.Settings.PrintTotalRecords = false;

            report.Settings.RowSeparatorLine.Thickness = 1;
            report.Settings.RowSeparatorLine.Color = Color.Black;

        }

        #endregion

        #region Print Events

        private void QueryPageSettings(object sender, QueryPageSettingsEventArgs e)
        {
            e.PageSettings = pageSettings;
        }

        #endregion

        #region UI Events

        private void btnZoomOut_Click(object sender, System.EventArgs e)
        {
            if (pp.Zoom - 0.1 > 0)
                pp.Zoom -= 0.1;

            sb.Panels[2].Text = "Zoom Factor: " + ((int)(pp.Zoom * 100)).ToString();
        }

        private void btnZoomIn_Click(object sender, System.EventArgs e)
        {
            pp.Zoom += 0.1;
            sb.Panels[2].Text = "Zoom Factor: " + ((int)(pp.Zoom * 100)).ToString();
        }

        private void InitNumPagesControl()
        {
            if (numPages > 0)
                nePages.Maximum = numPages;
        }

        private void cm_Popup(object sender, System.EventArgs e)
        {

        }

        private void NextPage()
        {
            if (nePages.Value < nePages.Maximum)
            {
                mnNextPage.Enabled = true;
                nePages.Value++;
            }
            else
                mnNextPage.Enabled = false;



        }

        private void btnPreviousPage_Click(object sender, System.EventArgs e)
        {
            PreviousPage();
        }

        private void btnTFirst_Click(object sender, System.EventArgs e)
        {
            FirstPage();
        }

        private void btnTLast_Click(object sender, System.EventArgs e)
        {
            LastPage();
        }

        private void btnNextPage_Click(object sender, System.EventArgs e)
        {
            NextPage();
        }

        private void FirstPage()
        {
            try
            {
                nePages.Value = nePages.Minimum;
            }
            catch { }

        }

        private void LastPage()
        {
            try
            {
                nePages.Value = nePages.Maximum;
            }
            catch { }
        }

        private void PreviousPage()
        {
            if (nePages.Value > nePages.Minimum)
            {
                mnPreviousPage.Enabled = true;
                nePages.Value--;
            }
            else
            {
                mnPreviousPage.Enabled = false;
                mnNextPage.Enabled = true;
            }



        }

        private void PageButtons_Click(object sender, System.EventArgs e)
        {
            int pageNumber = 0;

            if (sender != null && sender is Button && ((Button)sender).Tag != null)
            {
                if (Int32.TryParse(((Button)sender).Tag.ToString(), out pageNumber))
                {
                    nePages.Value = (decimal)pageNumber;
                }

            }

        }

        private void btnFilter_Click(object sender, System.EventArgs e)
        {
            if (DataTable == null || DataTable.Rows.Count <= 0)
            {
                MessageBox.Show("No records to filter", "Reports");
                return;
            }

         

            filter.Table = this.DataTable;

            filter.ShowDialog();
        

            //MessageBox.Show(filter.HasFilters.ToString());

        
                //if (filter.HasFilters)
                //{
                    // MessageBox.Show("HasFilters");
                    //PrintReport(this.DataTable, PrintPageDisplay.PREVIEW);
                    GenerateReport(this.DataTable, PrintPageDisplay.PREVIEW);
               // }


        }

        private void neColumns_ValueChanged(object sender, System.EventArgs e)
        {
            pp.Columns = (int)neColumns.Value;
            UpdateStatusbar();
        }

        private void neRows_ValueChanged(object sender, System.EventArgs e)
        {
            pp.Rows = (int)neRows.Value;
            UpdateStatusbar();
        }

        private void nePages_ValueChanged(object sender, System.EventArgs e)
        {
            pp.StartPage = (int)nePages.Value - 1;

            display.ShowPage(Convert.ToInt32(nePages.Value - 1));


            UpdateStatusbar();
        }


        private void btnPrint_Click(object sender, System.EventArgs e)
        {
            Print();
        }

        private void Print()
        {
            if (PrinterInstalled())
            {
                document.Print();
               // pp.Document.Print();
            }
        }




        private void cbxZoom_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            switch (cbxZoom.SelectedIndex)
            {
                case 0:
                    pp.AutoZoom = true;
                    break;
                case 1:
                    pp.Zoom = 5;
                    break;
                case 2:
                    pp.Zoom = 2;
                    break;
                case 3:
                    pp.Zoom = 1.5;
                    break;
                case 4:
                    pp.Zoom = 1;
                    break;
                case 5:
                    pp.Zoom = 0.9;
                    break;
                case 6:
                    pp.Zoom = 0.8;
                    break;
                case 7:
                    pp.Zoom = 0.75;

                    break;
                case 8:
                    pp.Zoom = 0.70;

                    break;

                case 9:
                    pp.Zoom = 0.6;

                    break;

                case 10:
                    pp.Zoom = 0.5;
                    break;
                case 11:
                    pp.Zoom = 0.4;
                    break;
                case 12:
                    pp.Zoom = 0.3;
                    break;
                case 13:
                    pp.Zoom = 0.25;
                    break;
                case 14:
                    pp.Zoom = 0.2;
                    break;
                case 15:
                    pp.Zoom = 0.10;
                    break;


            }
            UpdateStatusbar();
        }


        #endregion

        #region Layout

        public void SaveLayout(Stream stream)
        {
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, this.report);
        }


        public void SaveLayout(String path)
        {
            Stream stream = null;
            try
            {
                stream = File.Open(@path, FileMode.Create, FileAccess.ReadWrite);
                SaveLayout(stream);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                MessageBox.Show(ex.InnerException.Message);

            }
            finally
            {
                if (stream != null) stream.Close();
            }
        }

        public void LoadLayout(Stream stream)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            this.report = (Report)formatter.Deserialize(stream);
        }

        #endregion

        #region Report Printing

        private bool PrinterInstalled()
        {
            int i = 0;
            foreach (string printer in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
            {
                i++;
            }

            if (i == 0)
            {
                MessageBox.Show("Reports requires a printer\nThere are currently no printers installed on this computer.\n Please add a printer", "No Printer Installed");
                return false;

            }
            else return true;

        }

        public void ShowPagedd()
        {
            //PictureBox dd = new PictureBox();
            //dd.ImageLocation = @"C:\1.bmp";

            //PictureBox dd1 = new PictureBox();
            //dd1.ImageLocation = @"C:\2.gif";

            //display1.PageImages.Add(dd);
            //display1.PageImages.Add(dd1);

            //display1.ShowPage(0);

        }

        #region Print Report
        public void PrintReport(DataTable table, PrintPageDisplay pageDisplay)
        {

            if (!PrinterInstalled())
            {

                return;
            }

            currentTable = table;

            if (table == null && this.report.Settings.ReportType != ReportType.FreeForm)
            {
                MessageBox.Show("No records to print", "Report");
                return;
            }

            if (pageDisplay == PrintPageDisplay.PRINT)
            {
                try
                {
                    document.Print();
                }
                catch (InvalidPrinterException e)
                {
                    MessageBox.Show("InvalidPrinterException\n\nDetails\n" + e.Message, "Reports");
                }
            }
            else
            {
                pp.Document = document;
                pp.InvalidatePreview();
            }

        }


        public void GenerateReport(DataTable table, PrintPageDisplay pageDisplay)
        {
            currentTable = table;

            if (table == null && this.report.Settings.ReportType != ReportType.FreeForm)
            {
                MessageBox.Show("No records to print", "Report");
                return;
            }
         

            recordIndex = 0;
            hasMorePages = true;
            display.PageImages.Clear();
            display.ClearImages();

            ClearPanelControls();

         
            display.Invalidate();

            PrintPage2();
            this.Invalidate();

          
        }



        /// <summary>
        /// Prints the report.  You have to manually supply a datatable to the DataTable property
        /// </summary>
        /// <param name="pageDisplay"></param>
        public void PrintReport(PrintPageDisplay pageDisplay)
        {
            if (!PrinterInstalled())
                return;

            PrintReport(currentTable, pageDisplay);
        }

        #endregion

        #region Print Page


        /// <summary>
        /// Responsible for calling the Print() procedure for each page.
        /// Called by OS
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                recordIndex = Print(currentTable, recordIndex, e);

                if (e.HasMorePages == false)
                {
                    InitNumPagesControl();

                    if (currentTable != null)
                        currentTable.DefaultView.RowFilter = String.Empty;

                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Report Error\n\nDetails:\n" + ex.Message, "Report");
            }
        }

        private void PrintPage2()
        {
            try
            {
                while (hasMorePages)
                {
                    recordIndex = Print2(currentTable, recordIndex);
                    // MessageBox.Show("has more pages:" + hasMorePages.ToString());
                    if (hasMorePages == false)
                    {
                        InitNumPagesControl();

                        if (currentTable != null)
                            currentTable.DefaultView.RowFilter = String.Empty;
                        break;

                    }
                }


                display.ShowPage(0);
               // pnlPage.Visible = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Report Error\n\nDetails:\n" + ex.Message, "Report");
            }
        }

        #endregion

        #region Print Header

        /// <summary>
        /// Responsible for drawing the report.Settings.Header of the report
        /// </summary>
        /// <param name="yPos">top margin</param>
        /// <param name="numLines">the starting line to draw.  Used to skip a line</param>
        /// <param name="e"></param>
        private void PrintHeader(ref int yPos, ref int numLines, PrintPageEventArgs e)
        {
            if (report.Settings.Header == null) return;

            Pen pen = null;
            StringFormat sf = null;

            try
            {
                pen = new Pen(Brushes.Black);

                //For formating the report.Settings.Header
                sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;

                //Create the rectangle to draw the company name into
                Rectangle rect = new Rectangle(e.PageBounds.X, e.MarginBounds.Top, e.PageBounds.Width, (int)report.Settings.HeaderFont.GetHeight(e.Graphics));

                //Draw the company name in the center of the report
                e.Graphics.DrawString(report.Settings.Header.CompanyName, report.Settings.SubHeaderFont, Brushes.Black, rect, sf);

                SkipLine(ref yPos, ref numLines);

                //Adjust the rectangle down to one line
                rect.Y = yPos;

                //Draw the title of the report
                Debug.WriteLine("Drawing Header");
                e.Graphics.DrawString(report.Settings.Header.ReportTitle, report.Settings.HeaderFont, Brushes.Black, rect, sf);

                SkipLine(ref yPos, ref numLines);
            }
            finally
            {
                pen.Dispose();
                sf.Dispose();
            }

        }

        #endregion

        #region Totals

        private void PrintTotals(RowCellInfo cellInfo, SolidBrush myBrush, int x, float y, PrintPageEventArgs e)
        {
            SizeF size = e.Graphics.MeasureString(cellInfo.SummaryText + cellInfo.NumberCollection.GetSum().ToString(cellInfo.SummaryFormatString.Trim()), cellInfo.RowCell.Font);

            if (cellInfo.RowCell.ExtendToMargin)
            {
                int rightMargin = e.MarginBounds.Right;

                x = rightMargin - (int)size.Width;
            }
            else
                x = x - (int)size.Width;

            //Print Totals
            Debug.WriteLine("Printing Totals");
            switch (cellInfo.FunctionType)
            {
                case FunctionType.Average:
                    e.Graphics.DrawString(cellInfo.AverageText + cellInfo.NumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Summary:
                    // MessageBox.Show(cellInfo.NumberCollection.GetSum().ToString());
                    e.Graphics.DrawString(cellInfo.SummaryText + cellInfo.NumberCollection.GetSum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Maximum:
                    e.Graphics.DrawString(cellInfo.MaximumText + cellInfo.NumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Minimum:
                    e.Graphics.DrawString(cellInfo.MinimumText + cellInfo.NumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Count:
                    e.Graphics.DrawString(cellInfo.CountText + cellInfo.NumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
            }

        }

        private void ConfigureFunction(RowCellInfo cellInfo)
        {
            if (cellInfo.NumberCollection == null)
            {
                cellInfo.NumberCollection = new NumberCollection();
                cellInfo.TotalNumberCollection = new NumberCollection();
            }

            if (cellInfo.FunctionType == FunctionType.Count)
            {
                if (!(cellInfo.RowCell.Text == report.Settings.NullValue))
                {
                    cellInfo.NumberCollection.Add(new Number());
                    cellInfo.TotalNumberCollection.Add(new Number());
                }
            }
            else
            {
                if (!(cellInfo.RowCell.Text == report.Settings.NullValue))
                {
                    try
                    {
                        double number = Double.Parse(cellInfo.RowCell.Text.Trim());
                        //MessageBox.Show("Adding:"+ number.ToString());
                        cellInfo.NumberCollection.Add(new Number(number));
                        cellInfo.TotalNumberCollection.Add(new Number(number));
                    }
                    catch (Exception ec)
                    {
                        MessageBox.Show("Error:Configure Function for:" + cellInfo.DatabaseField + ":" + ec.Message);
                    }
                }
                else
                {
                    cellInfo.NumberCollection.Add(new Number(0));
                    cellInfo.TotalNumberCollection.Add(new Number(0));
                }
            }

        }

        #endregion


        #region Update Controls

        private int Print2(DataTable table, int recordIndex)
        {
           // MessageBox.Show("Print2");

            int pageSize_Width = 816;
            int pageSize_Height = 1056;

            if (PageSettings.Landscape)
            {
                pageSize_Width = 1056;
                pageSize_Height = 816;
                marginBounds_Left = 48;
                marginBounds_Width = 960;
                marginBounds_Right = 1008;
                marginBounds_Top = 48;
                marginBounds_Bottom = 768;
                marginBounds_Height = 720;
                marginBounds_X = 48;
                marginBounds_Y = 48;
                pageBounds_Width = 1056;
                pageBounds_Height = 816;
                leftMargin = 48;

            }
            else
            {
                pageSize_Width = 1056; 
                pageSize_Height = 816;
            }

            /////////////
            Bitmap image = new Bitmap(pageSize_Width, pageSize_Height);
            Graphics g = Graphics.FromImage(image);

            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBilinear;
            g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            //g.DrawString("Page:" + currentPage.ToString(), report.Settings.SubHeaderFont, report.Settings.MyBrush, 10, 10);

            //PictureBox dd = new PictureBox();
            //dd.Size = new Size(pageSize_Width, pageSize_Height);
            //dd.Image = image;
            //display.PageImages.Add(dd);

            //  MessageBox.Show(display1.PageImages.Count.ToString());





            /////////////




            int yPos = 0;// e.MarginBounds.Top;  //Top margin position to start printing
            // int leftMargin = 0;// e.MarginBounds.Left;
            //  int numLines = 34;// (image.Height / 96) / report.Settings.HeaderFont.Height;  //numlines changes if in Landscape mode

            int numLines = marginBounds_Height / report.Settings.HeaderFont.Height;
            //int pageBounds_Width=300;
            // int marginBounds_Bottom=300;


            numLines--;

            Debug.WriteLine("Number of Lines:" + numLines.ToString());
            Debug.WriteLine("Top Margins:" + yPos.ToString());
            Debug.WriteLine("Font Height:" + report.Settings.HeaderFont.Height);

            // if (report.Settings.ReportType == ReportType.FreeForm)
            //    report.Settings.PrintHeading = PrintHeading.No;

            //Print report report.Settings.Header on first page of report
            if (recordIndex == 0 && report.Settings.PrintHeading == PrintHeading.OnFirstPage)
            {
                PrintHeader2(ref yPos, ref numLines, g);
            }
            else if (report.Settings.PrintHeading == PrintHeading.OnAllPages)
            {
                //Print report report.Settings.Header on all pages of report
                PrintHeader2(ref yPos, ref numLines, g);
            }

            //If this is a free form report then PrintFreeForm
            if (report.Settings.ReportType == ReportType.FreeForm)
            {
                return PrintFreeForm2(table, numLines, recordIndex, yPos, g);
            }

            //No records to print
            if (table != null && table.DefaultView.Count == 0)
            {
                g.DrawString("NO RECORDS", new Font(report.Settings.SubscriptFont, FontStyle.Bold), myBrush, leftMargin, yPos);
                hasMorePages = false;
               // MessageBox.Show("NO RECORDS");

                PictureBox dd = new PictureBox();
                dd.Size = new Size(pageSize_Width, pageSize_Height);
                dd.Image = image;
                display.PageImages.Add(dd);

                return 0;

            }

            Debug.WriteLine("Number of Lines:" + numLines.ToString());
            Debug.WriteLine("Top Margins:" + yPos.ToString());

            //Print date on report
            if (report.Settings.ReportDate != PrintReportDateLocation.None)
            {
                PrintDate2(this.report.Settings.ReportDate, g);
                if (report.Settings.ReportDate == PrintReportDateLocation.LeftTop ||
                    report.Settings.ReportDate == PrintReportDateLocation.RightTop)

                    SkipLine(ref yPos, ref numLines);
            }

            //Print the total amount of records in this table
            if (report.Settings.PrintTotalRecords)
            {
                SizeF size = g.MeasureString(report.Settings.TotalText + ":" + table.Rows.Count.ToString(), report.Settings.SubHeaderFont);
                g.DrawString(report.Settings.TotalText + ":" + table.Rows.Count.ToString(), report.Settings.SubHeaderFont, Brushes.Black, marginBounds_Right - (int)size.Width, yPos);
            }

            //Print any text section for this report
            foreach (TextSection ts in report.Data.TextSections)
            {
                DrawTextSection2(ts, leftMargin, yPos, ref rect, myBrush, g);
                SkipLine(ref yPos, ref numLines);
            }

            SkipLine(ref yPos, ref numLines);

            //Print Hierarchy Report
            if (report.Settings.ReportType == ReportType.Hierachy)
            {
                recordIndex = PrintGroup2(table, numLines, recordIndex, ref yPos, g);
            }

            //Print General List Report
            else if (report.Settings.ReportType == ReportType.GeneralList)
            {
                //MessageBox.Show("About to PrintGeneralListReport2");
                recordIndex = PrintGeneralListReport2(table, numLines, recordIndex, yPos, g);
            }

            if (report.Settings.PrintPageNumbers)
            {
                //Print page number at the bottom of the page
                g.DrawString("[ " + currentPage.ToString() + " ]", report.Settings.SubscriptFont, Brushes.Black, pageBounds_Width / 2, (float)marginBounds_Bottom);
            }

            int end = table.DefaultView.Count;

            if (recordIndex >= end)
            {
                SkipLine(ref yPos, ref numLines);

                //Reset for group reports
                deltaText = String.Empty;
                deltaText2 = String.Empty;

                //Print Grand Totals
                PrintGrandTotals2(myBrush, linePen, leftMargin, ref yPos, g);

                hasMorePages = false;

                //Reset variables
                recordIndex = 0;
                numPages = currentPage;

                PictureBox dd = new PictureBox();
                dd.Size = new Size(pageSize_Width, pageSize_Height);
                dd.Image = image;
                display.PageImages.Add(dd);

                AddPageButtons(numPages, image);

               

              
                //MessageBox.Show("Added Page:" + display.PageImages.Count.ToString());



                currentPage = 1;

            }
            else
            {
                currentPage++;
                hasMorePages = true;

                PictureBox dd = new PictureBox();
                dd.Size = new Size(pageSize_Width, pageSize_Height);
                dd.Image = image;
                display.PageImages.Add(dd);


            }


            UpdateStatusbar();


            return recordIndex;
        }

        private void PrintHeader2(ref int yPos, ref int numLines, Graphics g)
        {
            if (report.Settings.Header == null) return;

            Pen pen = null;
            StringFormat sf = null;

            try
            {
                pen = new Pen(Brushes.Black);

                //For formating the report.Settings.Header
                sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;

                //Create the rectangle to draw the company name into
                Rectangle rect = new Rectangle(0, 0, pageBounds_Width, (int)report.Settings.HeaderFont.GetHeight(g));

                //Draw the company name in the center of the report
                g.DrawString(report.Settings.Header.CompanyName, report.Settings.SubHeaderFont, Brushes.Black, rect, sf);

                SkipLine(ref yPos, ref numLines);

                //Adjust the rectangle down to one line
                rect.Y = yPos;

                //Draw the title of the report
                Debug.WriteLine("Drawing Header");
                g.DrawString(report.Settings.Header.ReportTitle, report.Settings.HeaderFont, Brushes.Black, rect, sf);

                SkipLine(ref yPos, ref numLines);
            }
            finally
            {
                pen.Dispose();
                sf.Dispose();
            }

        }

        private int PrintFreeForm2(DataTable table, int numLines, int recordIndex, float yPos, Graphics g)
        {
            Debug.WriteLine("Free Form Report");
            // int leftMargin = 0;// e.MarginBounds.Left;

            //Initialize dummy rect for drawing text
            RectangleF rect = new RectangleF(0f, 0f, 0f, 0f);

            linePen.Width = (float)report.Settings.RowSeparatorLine.Thickness;

            g.PageUnit = GraphicsUnit.Inch;

            //Draw all lines in this report
            Debug.WriteLine("Drawing Lines");
            foreach (LineInfo line in report.Data.Lines)
            {
                DrawLine2(line, linePen, g);
            }

            //Draw all images in this report
            Debug.WriteLine("Drawing Images");
            foreach (ReportImage reportImage in report.Data.Images)
            {
                g.DrawImage(reportImage.Image, reportImage.X * CENTIMETER_TO_INCH, reportImage.Y * CENTIMETER_TO_INCH);
            }

            //Draw all Rectangles in this report
            float originalPenThickness = linePen.Width;
            Debug.WriteLine("Drawing Rectangles");
            foreach (ReportRectangle rr in report.Data.Rectangles)
            {
                DrawRectangle(rr, linePen, g);
            }

            linePen.Width = originalPenThickness;

            //Write all values from table
            if (report.Settings.UseTableInFreeForm && table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    foreach (RowCellInfo cell in report.Data.FreeFormCells)
                    {
                        try
                        {
                            if (cell.DatabaseField.Trim() != String.Empty)
                            {
                                cell.RowCell.Text = row.IsNull(cell.DatabaseField) ? report.Settings.NullValue : row[cell.DatabaseField].ToString();
                            }

                            DrawCell(cell.RowCell, cell.X * CENTIMETER_TO_INCH, cell.Y * CENTIMETER_TO_INCH, ref rect, myBrush, g);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Report Error\n\nDetails:\n" + ex.Message, "Reports");
                        }
                    }
                }
            }
            else
            {

                foreach (RowCellInfo cell in report.Data.FreeFormCells)
                {
                    DrawCell(cell.RowCell, cell.X * CENTIMETER_TO_INCH, cell.Y * CENTIMETER_TO_INCH, ref rect, myBrush, g);
                }
                Debug.WriteLine("Finish Drawing Cells");

            }

            hasMorePages = false;

            return recordIndex;
        }

        private void DrawLine2(LineInfo lineInfo, Pen pen, Graphics g)
        {
            pen.Width = (float)lineInfo.Thickness / 96f;
            pen.Color = lineInfo.Color;

            g.DrawLine(pen, lineInfo.X * CENTIMETER_TO_INCH, lineInfo.Y * CENTIMETER_TO_INCH, lineInfo.X1 * CENTIMETER_TO_INCH, lineInfo.Y1 * CENTIMETER_TO_INCH);
        }

        private void PrintColumns2(ColumnCellCollection columns, int position, ref int yPos, ref Rectangle rect, SolidBrush myBrush, Pen linePen, Graphics g)
        {
            foreach (ColumnCell column in columns)
            {
                column.Height = report.Settings.HeaderFont.Height;
                DrawColumn2(column, position, yPos, ref rect, myBrush, linePen, g);
                position += column.Width;
            }

        }

        private void PrintColumns2(SolidBrush myBrush, Pen linePen, Rectangle rect, float yPos, Graphics g)
        {
            //Draw Columns from left margins

            int x = marginBounds_Left;
            foreach (ColumnCell columnCell in this.report.Data.ColumnCellCollection)
            {
                //Draw the column
                columnCell.Height = report.Settings.HeaderFont.Height;
                DrawColumn2(columnCell, x, (int)yPos, ref rect, myBrush, linePen, g);

                //Draw a rectangle around the column until the bottom of the page
                //if (report.Settings.PrintTableGrid)
                //DrawRectangle(x,(int)yPos,columnCell.Width,e.MarginBounds.Bottom-(int)yPos,linePen,e);

                x += columnCell.Width;
            }

        }

        private void PrintDate2(PrintReportDateLocation location, Graphics g)
        {
            //int marginBounds_Left = 0;
            //int marginBounds_Top = 0;
            //int marginBounds_Right = 100;
            //int marginBounds_Bottom = 100;

            switch (location)
            {
                case PrintReportDateLocation.LeftTop:
                    {
                        g.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, marginBounds_Left, marginBounds_Top);
                        break;
                    }
                case PrintReportDateLocation.LeftBottom:
                    {
                        g.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, marginBounds_Left, marginBounds_Bottom);
                        break;
                    }
                case PrintReportDateLocation.RightTop:
                    {
                        SizeF size = g.MeasureString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont);

                        g.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, marginBounds_Right - (int)size.Width, marginBounds_Top);
                        break;
                    }

                case PrintReportDateLocation.RightBottom:
                    {
                        SizeF size = g.MeasureString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont);
                        g.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, marginBounds_Right - (int)size.Width, marginBounds_Bottom);
                        break;
                    }

            }

        }

        private void DrawTextSection2(TextSection textSection, int x, int y, ref Rectangle rect, SolidBrush brush, Graphics g)
        {
            //int marginBounds_Right = 100;
            //Check if to draw this column all the way to the end margin
            if (textSection.ExtendToMargin)
            {
                textSection.Width = marginBounds_Right - x;
                rect.Width = marginBounds_Right - x;
            }
            else
                rect.Width = textSection.Width;

            if (textSection.Height == 0)
                textSection.Height = report.Settings.HeaderFont.Height;

            rect.Height = textSection.Height;
            rect.X = x;
            rect.Y = y;

            //Draw background color
            brush.Color = textSection.BackgroundColor;
            g.FillRectangle(brush, rect);

            //Align the text in the columns
            defaultStringFormat.Alignment = (StringAlignment)((int)textSection.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)textSection.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = (StringFormatFlags)((int)textSection.CellFormat.FormatFlags);
            defaultStringFormat.Trimming = (StringTrimming)((int)textSection.CellFormat.Trimming);

            brush.Color = textSection.ForeColor;

            //Draw the column
            g.DrawString(textSection.Text, textSection.Font, brush, rect, defaultStringFormat);

            if (textSection.Outline)
            {
                g.DrawRectangle(Pens.Black, rect);
            }
        }

        private void DrawRowSeparatorLine2(LineInfo lineInfo, int y, Pen pen, Graphics g)
        {
            // marginsBounds_X = 0;
            // marginsBounds_Right = 0;
            g.DrawLine(pen, marginBounds_X, y, marginBounds_Right, y);
        }

        private int PrintGroup2(DataTable table, int numLines, int recordIndex, ref int yPos, Graphics g)
        {

            //  int leftMargin = 0;
            // int marginBounds_Left = 0;

            linePen.Width = (float)report.Settings.RowSeparatorLine.Thickness;

            //Initialize dummy rect for drawing text
            Rectangle rect = new Rectangle(0, 0, 0, 0);

            //This variable will be used in the 'Hiercarchy' report type
            //to know when to group rows together
            string databaseField = String.Empty;

            numLines--; //Decrease by one so that an extra line is always left at the bottom
            //in case totals need to be printed

            Debug.WriteLine("Print Group Num Lines:" + numLines);

            int counter = numLines;           //Will be used to count how many lines are used

            int group0XPosition = leftMargin;  //Level 0 Margins
            int group1XPosition = leftMargin + report.Data.Group.Indent;  //Level 1 Margins
            int group2XPosition = leftMargin + report.Data.SubGroup.Indent; // Level 2 Margins

            StringCollection deltaDatabaseFields = new StringCollection(); //used to holds the database fields for the first Level
            StringCollection deltaDatabaseFields2 = new StringCollection(); //used to holds the database fields for the first Level

            //Get the delta database fields that will be used to create table hirarchies Level 1
            foreach (RowCellInfo cellInfo in report.Data.Group.RowCellInfos)
            {
                if (cellInfo.Delta)
                {
                    deltaDatabaseFields.Add(cellInfo.DatabaseField);
                    Debug.WriteLine(cellInfo.DatabaseField);
                }
            }

            //Get the delta database fields that will be used to create table hirarchies Level 2
            foreach (RowCellInfo cellInfo in report.Data.SubGroup.RowCellInfos)
            {
                if (cellInfo.Delta)
                {
                    deltaDatabaseFields2.Add(cellInfo.DatabaseField);
                }
            }

            try
            {

                int end = table.DefaultView.Count;

                //Start 
                while (numLines > 0 && recordIndex < end)
                {
                    Debug.WriteLine("Record Index:" + recordIndex.ToString());

                    //Get the row[recordIndex] from the datatable 
                    //DataRow row = table.Rows[recordIndex];
                    DataRow row = table.DefaultView[recordIndex].Row;

                    ///////////////////////LEVEL 1////////////////////////////
                    Debug.WriteLine("Level 1 Printing");

                    //Create the delta Text
                    string deltaValues = String.Empty;

                    //Get the contcatenated strings of all the row cell's values
                    foreach (string s in deltaDatabaseFields)
                    {
                        try
                        {
                            deltaValues += row.IsNull(s) ? report.Settings.NullValue : row[s].ToString();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Field '" + s + "' does not exist in table\n\nDetails:\n" + ex.Message);
                        }
                    }

                    if (deltaValues != deltaText)  //This will always be true for the first record
                    {

                        //if skip page on different
                        if (counter != numLines && report.Data.Group.SkipPageOnChange)
                        {
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);

                            PrintGrandTotals2(myBrush, linePen, marginBounds_Left, ref yPos, g);
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);
                            return recordIndex;
                        }

                        deltaText = deltaValues;   //Do this for comparasins later

                        //Set deltaText2 to blank in case their is a second level to this report
                        //containing delta text
                        deltaText2 = "";


                        if (counter != numLines)
                        {
                            SkipLine(ref yPos, ref numLines);
                        }

                        //Print cells for Level 1
                        PrintRowCells2(report.Data.Group, row, group0XPosition, ref yPos, ref rect, myBrush, g, recordIndex, ref numLines, deltaText, deltaDatabaseFields);

                        //Skip Line
                        SkipLine(ref yPos, ref numLines);
                        if (numLines <= 0)
                        {
                            return recordIndex++;
                        }

                        //Draw a row separator
                        if (report.Settings.PrintRowSeparator)
                            DrawRowSeparatorLine2(report.Settings.RowSeparatorLine, (int)yPos, linePen, g);

                        if (report.Data.SubGroup.Columns.Count > 0)
                        {

                            SkipLine(ref yPos, ref numLines);
                            //Print the Subheading for Level 2 columns (if any)
                            g.DrawLine(linePen, leftMargin, yPos - report.Settings.HeaderFont.Height, leftMargin, yPos + report.Settings.HeaderFont.Height / 2);
                            g.DrawLine(linePen, leftMargin, yPos + report.Settings.HeaderFont.Height / 2, leftMargin + report.Data.SubGroup.Indent, yPos + report.Settings.HeaderFont.Height / 2);
                            PrintColumns2(report.Data.SubGroup.Columns, leftMargin + report.Data.Group.Indent, ref yPos, ref rect, myBrush, linePen, g);

                            if (report.Data.SubGroup2.RowCellInfos.Count == 0)
                            {
                                SkipLine(ref yPos, ref numLines);
                                if (numLines <= 0)
                                {
                                    return recordIndex++;

                                }
                            }
                        }

                    }

                    ///////////////////LEVEl 2 PRINTING/////////////////////////////////////////

                    //Create the delta Text
                    string deltaValues2 = String.Empty;
                    StringCollection fields = new StringCollection();


                    //Get the contcatenated strings of all the row cells

                    if (deltaDatabaseFields2.Count == 0)
                    {
                        Debug.WriteLine("No Level 3");
                        Debug.WriteLine("Current record Index:" + recordIndex.ToString());
                        PrintRowCells2(report.Data.SubGroup, row, group1XPosition, ref yPos, ref rect, myBrush, g, recordIndex, ref numLines, deltaText, deltaDatabaseFields);

                    }
                    else
                    {
                        //There is a third level to this report

                        //Create the delta values
                        foreach (string s in deltaDatabaseFields2)
                        {
                            deltaValues2 += row.IsNull(s) ? report.Settings.NullValue : row[s].ToString();
                        }

                        //Combine the delta fields from Level 1 and Level 2
                        foreach (string s in deltaDatabaseFields)
                        {
                            fields.Add(s);
                        }

                        foreach (string s in deltaDatabaseFields2)
                        {
                            fields.Add(s);
                        }

                        if (deltaValues2 != deltaText2)
                        {
                            deltaText2 = deltaValues2;

                            SkipLine(ref yPos, ref numLines);
                            PrintRowCells2(report.Data.SubGroup, row, group1XPosition, ref yPos, ref rect, myBrush, g, recordIndex, ref numLines, deltaText + deltaText2, fields);

                            SkipLine(ref yPos, ref numLines);
                            if (numLines <= 0)
                            {

                                return recordIndex++;

                            }

                            SkipLine(ref yPos, ref numLines);
                            g.DrawLine(linePen, leftMargin + report.Data.Group.Indent, yPos - report.Settings.HeaderFont.Height, leftMargin + report.Data.Group.Indent, yPos + report.Settings.HeaderFont.Height / 2);
                            g.DrawLine(linePen, leftMargin + report.Data.Group.Indent, yPos + report.Settings.HeaderFont.Height / 2, leftMargin + report.Data.SubGroup2.Indent, yPos + report.Settings.HeaderFont.Height / 2);
                            PrintColumns2(report.Data.SubGroup2.Columns, group2XPosition, ref yPos, ref rect, myBrush, linePen, g);
                            SkipLine(ref yPos, ref numLines);

                        }

                    }


                    ///////////////////LEVEL 3 PRINTING///////////////////////////////
                    if (report.Data.SubGroup2.RowCellInfos.Count == 0)
                    {
                        Debug.WriteLine("CONTINUE: Increase record Index");
                        recordIndex++;
                        SkipLine(ref yPos, ref numLines);
                        continue;      //No Level 3: Skip Level three printing
                    }
                    else
                    {
                        Debug.WriteLine("Level3:" + deltaText + deltaText2);
                        PrintRowCells2(report.Data.SubGroup2, row, group2XPosition, ref yPos, ref rect, myBrush, g, recordIndex, ref numLines, deltaText + deltaText2, fields);
                        //SkipLine(ref yPos,ref numLines);
                    }


                    SkipLine(ref yPos, ref numLines);
                    Debug.WriteLine("Increase record Index");
                    recordIndex++;


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Report Error");
            }

            Debug.WriteLine("END Print Group Num Lines:" + numLines);

            return recordIndex;
        }

        private void PrintGrandTotals2(SolidBrush myBrush, Pen linePen, int x, ref int y, Graphics g)
        {

            linePen.Width += 2;

            g.DrawLine(linePen, marginBounds_Left, y, pageBounds_Width - marginBounds_Y, y);

            Rectangle rect = new Rectangle(0, 0, 0, 0);

            linePen.Width -= 2;

            decimal first = 0, second = 0;

            Stack s = new Stack(2);

            y = y + 5;

            foreach (RowCellInfo cellInfo in report.Data.Group.RowCellInfos)
            {
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    GrandSummaryCell gsc = cellInfo.GrandSummaryCell;
                    gsc.ColumnCell.Height = report.Settings.HeaderFont.Height;
                    gsc.RowCell.Height = report.Settings.HeaderFont.Height;

                    switch (cellInfo.FunctionType)
                    {
                        case FunctionType.Average:
                            g.DrawString(cellInfo.AverageText + cellInfo.TotalNumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;

                        case FunctionType.Summary:

                            double sum = cellInfo.TotalNumberCollection.GetSum();
                            if (report.Settings.CalculatedField.IndexOf(cellInfo.DatabaseField) != -1)
                            {
                                s.Push(sum);
                            }

                            gsc.RowCell.Text = sum.ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                        case FunctionType.Maximum:
                            g.DrawString(cellInfo.MaximumText + cellInfo.TotalNumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Minimum:
                            g.DrawString(cellInfo.MinimumText + cellInfo.TotalNumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Count:
                            g.DrawString(cellInfo.CountText + cellInfo.TotalNumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                    }

                    x += gsc.RowCell.Width + 10;
                    cellInfo.TotalNumberCollection.Clear();
                }

            }

            foreach (RowCellInfo cellInfo in report.Data.SubGroup.RowCellInfos)
            {
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    GrandSummaryCell gsc = cellInfo.GrandSummaryCell;
                    gsc.ColumnCell.Height = report.Settings.HeaderFont.Height;
                    gsc.RowCell.Height = report.Settings.HeaderFont.Height;

                    switch (cellInfo.FunctionType)
                    {
                        case FunctionType.Average:
                            g.DrawString(cellInfo.AverageText + cellInfo.TotalNumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Summary:

                            double sum = cellInfo.TotalNumberCollection.GetSum();

                            if (report.Settings.CalculatedField.IndexOf(cellInfo.DatabaseField) != -1)
                            {
                                s.Push(sum);
                            }

                            gsc.RowCell.Text = sum.ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                        case FunctionType.Maximum:
                            g.DrawString(cellInfo.MaximumText + cellInfo.TotalNumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Minimum:
                            g.DrawString(cellInfo.MinimumText + cellInfo.TotalNumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Count:

                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                    }
                    x += gsc.RowCell.Width + 10;
                    cellInfo.TotalNumberCollection.Clear();

                }

            }

            foreach (RowCellInfo cellInfo in report.Data.SubGroup2.RowCellInfos)
            {

                if (cellInfo.FunctionType != FunctionType.None)
                {
                    GrandSummaryCell gsc = cellInfo.GrandSummaryCell;
                    gsc.ColumnCell.Height = report.Settings.HeaderFont.Height;
                    gsc.RowCell.Height = report.Settings.HeaderFont.Height;

                    switch (cellInfo.FunctionType)
                    {
                        case FunctionType.Average:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                        case FunctionType.Summary:

                            double sum = cellInfo.TotalNumberCollection.GetSum();

                            if (report.Settings.CalculatedField.IndexOf(cellInfo.DatabaseField) != -1)
                            {
                                s.Push(sum);
                            }
                            gsc.RowCell.Text = sum.ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);

                            break;
                        case FunctionType.Maximum:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                        case FunctionType.Minimum:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                        case FunctionType.Count:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn2(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                            DrawCell2(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
                            break;
                    }
                    x += gsc.RowCell.Width + 10;
                    cellInfo.TotalNumberCollection.Clear();
                }
            }

            if (report.Settings.CalculatedField != String.Empty && s.Count > 0)
            {
                second = Convert.ToDecimal(s.Pop());
                first = Convert.ToDecimal(s.Pop());

                GrandSummaryCell c = new GrandSummaryCell();
                c.RowCell.Font = new Font(c.RowCell.Font, FontStyle.Bold);

                c.GrandSummaryText = "BALANCE DUE";
                c.RowCell.Text = (first - second).ToString("C");
                c.RowCell.Height = report.Settings.HeaderFont.Height;
                c.ColumnCell.Height = report.Settings.HeaderFont.Height;
                c.ColumnCell.BackgroundColor = Color.Red;
                DrawColumn2(c.ColumnCell, x, y, ref rect, myBrush, linePen, g);
                DrawCell2(c.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, g);
            }
        }

        private void DrawColumn2(ColumnCell columnCell, int x, int y, ref Rectangle rect, SolidBrush brush, Pen linePen, Graphics g)
        {

            //Check if to draw this column all the way to the end margin
            if (columnCell.ExtendToMargin)
            {
                columnCell.Width = marginBounds_Right - x;
                rect.Width = marginBounds_Right - x;
            }
            else
                rect.Width = columnCell.Width;

            rect.Height = columnCell.Height;
            rect.X = x;
            rect.Y = y;

            //Draw column background
            brush.Color = columnCell.BackgroundColor;
            if (columnCell.BackgroundColor != Color.White)
                g.FillRectangle(brush, rect);


            //Print a separator line at the end of the column
            if (columnCell.PrintSeparator)
                g.DrawRectangle(Pens.Black, rect.X, rect.Y, rect.Width, rect.Height);

            //Align the text in the columns
            defaultStringFormat.Alignment = (StringAlignment)((int)columnCell.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)columnCell.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = (StringFormatFlags)((int)columnCell.CellFormat.FormatFlags);
            defaultStringFormat.Trimming = (StringTrimming)((int)columnCell.CellFormat.Trimming);

            brush.Color = columnCell.ForeColor;
            //Draw the column
            g.DrawString(" " + columnCell.Text, columnCell.Font, brush, rect, defaultStringFormat);

            if (columnCell.OutlineColumn)
            {
                linePen.Color = report.Settings.RowSeparatorLine.Color;
                g.DrawRectangle(linePen, rect);
            }

        }

        private void DrawCell2(RowCell cell, int x, int y, ref Rectangle rect, SolidBrush brush, Graphics g)
        {

            //Make sure that there is a value to print
            if (cell.Text.Trim() == String.Empty && cell.DontPrintIfBlank) return;

            if (cell.Width == 0) return;

            if (cell.ExtendToMargin)
                rect.Width = marginBounds_Right - x;
            else
                rect.Width = cell.Width;

            rect.Height = report.Settings.HeaderFont.Height;
            rect.X = x;
            rect.Y = y;


            brush.Color = cell.BackgroundColor;

            if (cell.BackgroundColor != Color.White)
            {
                g.FillRectangle(brush, rect);

            }

            brush.Color = cell.ForeColor;

            //Format the cell data
            defaultStringFormat.Alignment = (StringAlignment)((int)cell.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)cell.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = cell.CellFormat.FormatFlags;
            defaultStringFormat.Trimming = (StringTrimming)((int)cell.CellFormat.Trimming);

            if (cell.FormatString != String.Empty && cell.Text != report.Settings.NullValue)
            {
                string formattedString = String.Empty;
                switch (cell.DataType)
                {
                    case DataType.Int32:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", Int32.Parse(cell.Text));
                        break;
                    case DataType.Double:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", Double.Parse(cell.Text));
                        break;

                    case DataType.DateTime:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", DateTime.Parse(cell.Text));
                        break;

                    case DataType.String:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", cell.Text);
                        break;
                }
                cell.Text = formattedString;
            }

            if (cell.Image != null)
            {
                g.DrawImage(cell.Image, rect.X, rect.Y, cell.Image.Width, cell.Image.Height);

            }

            if (cell.LeftPadding > 0)
            {
                cell.Text = PadText(cell.Text.Trim(), cell.PaddingCharacter, cell.LeftPadding);
            }

            if (cell.Outline)
                g.DrawRectangle(Pens.Black, rect);

            g.DrawString(" " + cell.Text, cell.Font, brush, rect, defaultStringFormat);
        }

        private void PrintRowCells2(Group group, DataRow row, int position, ref int yPos, ref Rectangle rect, SolidBrush myBrush, Graphics g, int recordIndex, ref int numLines, string deltaText, StringCollection databaseFields)
        {

            //Debug.WriteLine("DeltaText:"+deltaText);
            //PrintStringCollection(databaseFields);

            Debug.WriteLine("PrintRowCell RecordIndex:" + recordIndex.ToString());

            foreach (RowCellInfo cellInfo in group.RowCellInfos)
            {
                cellInfo.RowCell.Text = row.IsNull(cellInfo.DatabaseField) ? report.Settings.NullValue : row[cellInfo.DatabaseField].ToString();//+"::"+numLines.ToString();

                ///////////CONFIGURE SUMMARIES
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    ConfigureFunction(cellInfo);
                }

                //Draw the cell
                DrawCell2(cellInfo.Text, position, (int)yPos, ref rect, myBrush, g);
                position += cellInfo.Text.Width;
                DrawCell2(cellInfo.RowCell, position, (int)yPos, ref rect, myBrush, g);


                //Determine if this is the last row for this grouping
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    //Debug.WriteLine("Function type for:"+cellInfo.RowCell.Text);
                    bool lastRow = false;

                    //Debug.WriteLine("Start Calling LastRow");
                    lastRow = IsLastRow(this.DataTable, recordIndex + 1, deltaText, databaseFields);
                    //Debug.WriteLine("finish Calling LastRow");

                    if (lastRow && !cellInfo.SuppressSummaryPrinting)
                    {
                        //Debug.WriteLine("Printing Function total");
                        //Skip a line

                        yPos += report.Settings.HeaderFont.Height;
                        //counter++;

                        //Print Totals
                        //  position + cellInfo.Text.Width


                        PrintTotals2(cellInfo, myBrush, position + cellInfo.RowCell.Width, yPos, g);

                        //Draw a line below the the totals
                        if (cellInfo.PrintSummaryLine)
                        {
                            report.Settings.SummaryLinePen.Color = cellInfo.SummaryLine.Color;
                            report.Settings.SummaryLinePen.Width = (float)cellInfo.SummaryLine.Thickness;
                            g.DrawLine(report.Settings.SummaryLinePen, position + cellInfo.Text.Width, yPos - 1, position + cellInfo.Text.Width + cellInfo.RowCell.Width - 5, yPos - 1);
                        }

                        yPos = yPos - report.Settings.HeaderFont.Height;

                        //Clear the collection that was used to stores all values calculated upon
                        if (cellInfo.NumberCollection != null) cellInfo.NumberCollection.Clear();
                    }
                    else
                    {
                        //Debug.WriteLine("Not Last row");
                    }
                }

                //Increase this variable in the case there might be more cells to draw
                position += cellInfo.RowCell.Width;
                ///////////END CONFIGURE SUMMARIES
            }
        }

        private void PrintTotals2(RowCellInfo cellInfo, SolidBrush myBrush, int x, float y, Graphics g)
        {
            SizeF size = g.MeasureString(cellInfo.SummaryText + cellInfo.NumberCollection.GetSum().ToString(cellInfo.SummaryFormatString.Trim()), cellInfo.RowCell.Font);



            if (cellInfo.RowCell.ExtendToMargin)
            {
                int rightMargin = marginBounds_Right;

                x = rightMargin - (int)size.Width;
            }
            else
                x = x - (int)size.Width;

            //Print Totals
            Debug.WriteLine("Printing Totals");
            switch (cellInfo.FunctionType)
            {
                case FunctionType.Average:
                    g.DrawString(cellInfo.AverageText + cellInfo.NumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Summary:
                    g.DrawString(cellInfo.SummaryText + cellInfo.NumberCollection.GetSum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Maximum:
                    g.DrawString(cellInfo.MaximumText + cellInfo.NumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Minimum:
                    g.DrawString(cellInfo.MinimumText + cellInfo.NumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
                case FunctionType.Count:
                    g.DrawString(cellInfo.CountText + cellInfo.NumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                    break;
            }

        }

        private int PrintGeneralListReport2(DataTable table, int numLines, int recordIndex, int yPos, Graphics g)
        {
           // MessageBox.Show("Printing General List");

            //  int leftMargin = 0;
            int rightMargin = marginBounds_Right;


            //Used for all painting. They are created here so that I don't have to
            //waste time creating them again in this procedure
            myBrush = new SolidBrush(report.Settings.RowSeparatorLine.Color);

            linePen.Width = (float)report.Settings.RowSeparatorLine.Thickness;


            //Initialize dummy rect for drawing text
            Rectangle rect = new Rectangle(0, 0, 0, 0);

            //Print the columns for this general list report
            PrintColumns2(myBrush, linePen, rect, yPos, g);

            //Skip line after columns
            SkipLine(ref yPos, ref numLines);

            Debug.WriteLine("General List NumLines:" + numLines.ToString());

            int counter = 0;

            //Used if there are more than one line per row
            int maxLines = report.Data.ColumnCellCollection.GetMaxAmountLinesUsedForRow();

            int originalY = yPos;

            //Get the numbers of record in the dataview
            int end = table.DefaultView.Count;

            //Start 
            try
            {
                while (counter < numLines && recordIndex < end)
                {

                    //We take the records from the defaultview because the user can filter
                    //the table and only want the filtered row to print.
                    DataRow row = table.DefaultView[recordIndex].Row;

                    //Print Row Data
                    int x2 = leftMargin;
                    int tempX = 0;
                    int y = yPos;

                    //Color alternate rows
                    if (report.Settings.ColorAlternateRows && counter % 2 == 1)
                    {
                        myBrush.Color = report.Settings.AlternateRowColor;
                        g.FillRectangle(myBrush, leftMargin, yPos, marginBounds_Width, maxLines * report.Settings.HeaderFont.Height);
                    }



                    //Print rows directly under their corresponding columns
                    foreach (ColumnCell columnCell in this.report.Data.ColumnCellCollection)
                    {
                        tempX = x2;

                        foreach (RowCellInfo cellInfo in columnCell.RowCellInfoCollection)
                        {


                            if (row.IsNull(cellInfo.DatabaseField)) cellInfo.RowCell.Text = report.Settings.NullValue;   //No data to print, so replace it with a the null value specified

                            else
                            {
                                //A lookup table is specified
                                if (cellInfo.LookupTable != null)
                                {
                                    DataTable lookupTable = cellInfo.LookupTable;
                                    string key = String.Empty;
                                    try
                                    {
                                        key = row[cellInfo.DatabaseField].ToString();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Report Error, Key '" + cellInfo.DatabaseField + "' not found in main table\n\nDetails:\n" + ex.Message);
                                    }

                                    int rowCounter = 0;  //Count how many rows you have searched
                                    foreach (DataRow r in lookupTable.Rows)
                                    {
                                        if (r[cellInfo.LookupKeyColumn].ToString() == key)
                                        {
                                            string columnValue = String.Empty;
                                            foreach (string column in cellInfo.MappedColumns)
                                            {
                                                columnValue += r[column].ToString();
                                            }
                                            cellInfo.RowCell.Text = columnValue;
                                            break;
                                        }
                                        rowCounter++;
                                    }

                                    //If equal to the size of the row collection then no matching records were
                                    //found
                                    if (rowCounter == lookupTable.Rows.Count)
                                    {
                                        cellInfo.RowCell.Text = "No Match";
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        cellInfo.RowCell.Text = row[cellInfo.DatabaseField].ToString();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Column'" + cellInfo.DatabaseField + "' not found in main table\n\nDetails:\n" + ex.Message);
                                    }
                                }
                            }

                            //Configure Summaries for this row cell (if any)
                            if (cellInfo.FunctionType != FunctionType.None)
                            {
                                ConfigureFunction(cellInfo);
                            }

                            //Draw the cell data and description text(if any)

                            DrawCell2(cellInfo.Text, tempX, y, ref rect, myBrush, g);
                            DrawCell2(cellInfo.RowCell, tempX + cellInfo.Text.Width, y, ref rect, myBrush, g);

                            //Determine if this is the last row for this grouping
                            if (cellInfo.FunctionType != FunctionType.None)
                            {
                                if (IsLastRow(table, recordIndex + 1))
                                {
                                    //Print Totals
                                    PrintTotals2(cellInfo, myBrush, tempX + cellInfo.RowCell.Width, yPos + report.Settings.HeaderFont.Height + 10, g);

                                    //Draw a line above and below the the totals
                                    if (cellInfo.PrintSummaryLine)
                                    {
                                        report.Settings.SummaryLinePen.Color = cellInfo.SummaryLine.Color;
                                        report.Settings.SummaryLinePen.Width = (float)cellInfo.SummaryLine.Thickness;
                                        g.DrawLine(report.Settings.SummaryLinePen, tempX + cellInfo.Text.Width, yPos + report.Settings.HeaderFont.Height + 5, tempX + columnCell.Width, yPos + report.Settings.HeaderFont.Height + 5);
                                        g.DrawLine(report.Settings.SummaryLinePen, tempX + cellInfo.Text.Width, yPos + report.Settings.HeaderFont.Height * 2 + 5, tempX + columnCell.Width, yPos + report.Settings.HeaderFont.Height * 2 + 5);
                                    }

                                    //Clear the collection that was used to stores all values calculated upon
                                    if (cellInfo.NumberCollection != null) cellInfo.NumberCollection.Clear();
                                }
                            }

                            //Draw the other cells in this column. A column can contain one or more
                            //database fields
                            if (columnCell.RowCellInfoPosition == RowCellInfoPosition.OneLine)
                                tempX += cellInfo.Text.Width + cellInfo.RowCell.Width;
                            else
                                y = y + report.Settings.HeaderFont.Height;

                        }

                        y = yPos;

                        x2 += columnCell.Width;
                        if (report.Settings.PrintTableGrid)
                        {
                            g.DrawLine(linePen, x2, (int)yPos, x2, (int)yPos + (maxLines * report.Settings.HeaderFont.Height));
                        }

                    }

                    counter += maxLines;
                    yPos = yPos + (maxLines * report.Settings.HeaderFont.Height);

                    if (report.Settings.PrintRowSeparator)
                    {
                        linePen.Color = report.Settings.RowSeparatorLine.Color;
                        DrawRowSeparatorLine2(report.Settings.RowSeparatorLine, (int)yPos, linePen, g);
                    }
                    recordIndex++;

                    //Outline Table with a line
                    if (report.Settings.OutlineTable && (counter == numLines || recordIndex == table.Rows.Count))
                    {
                        g.DrawLine(linePen, leftMargin, originalY, leftMargin, yPos);
                        g.DrawLine(linePen, rightMargin, originalY, rightMargin, yPos);
                        g.DrawLine(linePen, leftMargin, yPos, rightMargin, yPos);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Details:\n\n" + ex.Message, "Report Error");
            }

            return recordIndex;
        }
        #endregion

        #region Print (Main Printing Code)

        #region Print Free Form Report
        /// <summary>
        /// Responsible for printing on one sheet.
        /// </summary>
        /// <param name="table">Datatable used if report.Settings.UseTableInFreeForm=true;</param>
        /// <param name="numLines">used to skip lines</param>
        /// <param name="recordIndex">index of record (does not apply here.  Only used to end printing)</param>
        /// <param name="yPos">where to start printing</param>
        /// <param name="e"></param>
        /// <returns></returns>
        private int PrintFreeForm(DataTable table, int numLines, int recordIndex, float yPos, PrintPageEventArgs e)
        {
            Debug.WriteLine("Free Form Report");
            int leftMargin = e.MarginBounds.Left;

            //Initialize dummy rect for drawing text
            RectangleF rect = new RectangleF(0f, 0f, 0f, 0f);

            linePen.Width = (float)report.Settings.RowSeparatorLine.Thickness;

            e.Graphics.PageUnit = GraphicsUnit.Inch;

            //Draw all lines in this report
            Debug.WriteLine("Drawing Lines");
            foreach (LineInfo line in report.Data.Lines)
            {
                DrawLine(line, linePen, e);
            }

            //Draw all images in this report
            Debug.WriteLine("Drawing Images");
            foreach (ReportImage reportImage in report.Data.Images)
            {
                e.Graphics.DrawImage(reportImage.Image, reportImage.X * CENTIMETER_TO_INCH, reportImage.Y * CENTIMETER_TO_INCH);
            }

            //Draw all Rectangles in this report
            float originalPenThickness = linePen.Width;
            Debug.WriteLine("Drawing Rectangles");
            foreach (ReportRectangle rr in report.Data.Rectangles)
            {
                DrawRectangle(rr, linePen, e.Graphics);
            }

            linePen.Width = originalPenThickness;

            //Write all values from table
            if (report.Settings.UseTableInFreeForm && table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    foreach (RowCellInfo cell in report.Data.FreeFormCells)
                    {
                        try
                        {
                            if (cell.DatabaseField.Trim() != String.Empty)
                            {
                                cell.RowCell.Text = row.IsNull(cell.DatabaseField) ? report.Settings.NullValue : row[cell.DatabaseField].ToString();
                            }

                            DrawCell(cell.RowCell, cell.X * CENTIMETER_TO_INCH, cell.Y * CENTIMETER_TO_INCH, ref rect, myBrush, e.Graphics);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Report Error\n\nDetails:\n" + ex.Message, "Reports");
                        }
                    }
                }
            }
            else
            {

                foreach (RowCellInfo cell in report.Data.FreeFormCells)
                {
                    DrawCell(cell.RowCell, cell.X * CENTIMETER_TO_INCH, cell.Y * CENTIMETER_TO_INCH, ref rect, myBrush, e.Graphics);
                }
                Debug.WriteLine("Finish Drawing Cells");

            }

            e.HasMorePages = false;

            return recordIndex;
        }

        #endregion

        #region Print Group Report

        private int PrintGroup(DataTable table, int numLines, int recordIndex, ref int yPos, PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            int leftMargin = e.MarginBounds.Left;

            linePen.Width = (float)report.Settings.RowSeparatorLine.Thickness;

            //Initialize dummy rect for drawing text
            Rectangle rect = new Rectangle(0, 0, 0, 0);

            //This variable will be used in the 'Hiercarchy' report type
            //to know when to group rows together
            string databaseField = String.Empty;

            numLines--; //Decrease by one so that an extra line is always left at the bottom
            //in case totals need to be printed

            Debug.WriteLine("Print Group Num Lines:" + numLines);

            int counter = numLines;           //Will be used to count how many lines are used

            int group0XPosition = leftMargin;  //Level 0 Margins
            int group1XPosition = leftMargin + report.Data.Group.Indent;  //Level 1 Margins
            int group2XPosition = leftMargin + report.Data.SubGroup.Indent; // Level 2 Margins

            StringCollection deltaDatabaseFields = new StringCollection(); //used to holds the database fields for the first Level
            StringCollection deltaDatabaseFields2 = new StringCollection(); //used to holds the database fields for the first Level

            //Get the delta database fields that will be used to create table hirarchies Level 1
            foreach (RowCellInfo cellInfo in report.Data.Group.RowCellInfos)
            {
                if (cellInfo.Delta)
                {
                    deltaDatabaseFields.Add(cellInfo.DatabaseField);
                    Debug.WriteLine(cellInfo.DatabaseField);
                }
            }

            //Get the delta database fields that will be used to create table hirarchies Level 2
            foreach (RowCellInfo cellInfo in report.Data.SubGroup.RowCellInfos)
            {
                if (cellInfo.Delta)
                {
                    deltaDatabaseFields2.Add(cellInfo.DatabaseField);
                }
            }

            try
            {

                int end = table.DefaultView.Count;

                //Start 
                while (numLines > 0 && recordIndex < end)
                {
                    Debug.WriteLine("Record Index:" + recordIndex.ToString());

                    //Get the row[recordIndex] from the datatable 
                    //DataRow row = table.Rows[recordIndex];
                    DataRow row = table.DefaultView[recordIndex].Row;

                    ///////////////////////LEVEL 1////////////////////////////
                    Debug.WriteLine("Level 1 Printing");

                    //Create the delta Text
                    string deltaValues = String.Empty;

                    //Get the contcatenated strings of all the row cell's values
                    foreach (string s in deltaDatabaseFields)
                    {
                        try
                        {
                            deltaValues += row.IsNull(s) ? report.Settings.NullValue : row[s].ToString();
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Field '" + s + "' does not exist in table\n\nDetails:\n" + ex.Message);
                        }
                    }

                    if (deltaValues != deltaText)  //This will always be true for the first record
                    {

                        //if skip page on different
                        if (counter != numLines && report.Data.Group.SkipPageOnChange)
                        {
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);

                            PrintGrandTotals(myBrush, linePen, e.MarginBounds.Left, ref yPos, e);
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);
                            SkipLine(ref yPos, ref numLines);
                            return recordIndex;
                        }

                        deltaText = deltaValues;   //Do this for comparasins later

                        //Set deltaText2 to blank in case their is a second level to this report
                        //containing delta text
                        deltaText2 = "";


                        if (counter != numLines)
                        {
                            SkipLine(ref yPos, ref numLines);
                        }

                        //Print cells for Level 1
                        PrintRowCells(report.Data.Group, row, group0XPosition, ref yPos, ref rect, myBrush, e, recordIndex, ref numLines, deltaText, deltaDatabaseFields);

                        //Skip Line
                        SkipLine(ref yPos, ref numLines);
                        if (numLines <= 0)
                        {
                            return recordIndex++;
                        }

                        //Draw a row separator
                        if (report.Settings.PrintRowSeparator) DrawRowSeparatorLine(report.Settings.RowSeparatorLine, (int)yPos, linePen, e);

                        if (report.Data.SubGroup.Columns.Count > 0)
                        {

                            SkipLine(ref yPos, ref numLines);
                            //Print the Subheading for Level 2 columns (if any)
                            e.Graphics.DrawLine(linePen, leftMargin, yPos - report.Settings.HeaderFont.Height, leftMargin, yPos + report.Settings.HeaderFont.Height / 2);
                            e.Graphics.DrawLine(linePen, leftMargin, yPos + report.Settings.HeaderFont.Height / 2, leftMargin + report.Data.SubGroup.Indent, yPos + report.Settings.HeaderFont.Height / 2);
                            PrintColumns(report.Data.SubGroup.Columns, leftMargin + report.Data.Group.Indent, ref yPos, ref rect, myBrush, linePen, e);

                            if (report.Data.SubGroup2.RowCellInfos.Count == 0)
                            {
                                SkipLine(ref yPos, ref numLines);
                                if (numLines <= 0)
                                {
                                    return recordIndex++;

                                }
                            }
                        }

                    }

                    ///////////////////LEVEl 2 PRINTING/////////////////////////////////////////

                    //Create the delta Text
                    string deltaValues2 = String.Empty;
                    StringCollection fields = new StringCollection();


                    //Get the contcatenated strings of all the row cells

                    if (deltaDatabaseFields2.Count == 0)
                    {
                        Debug.WriteLine("No Level 3");
                        Debug.WriteLine("Current record Index:" + recordIndex.ToString());
                        PrintRowCells(report.Data.SubGroup, row, group1XPosition, ref yPos, ref rect, myBrush, e, recordIndex, ref numLines, deltaText, deltaDatabaseFields);

                    }
                    else
                    {
                        //There is a third level to this report

                        //Create the delta values
                        foreach (string s in deltaDatabaseFields2)
                        {
                            deltaValues2 += row.IsNull(s) ? report.Settings.NullValue : row[s].ToString();
                        }

                        //Combine the delta fields from Level 1 and Level 2
                        foreach (string s in deltaDatabaseFields)
                        {
                            fields.Add(s);
                        }

                        foreach (string s in deltaDatabaseFields2)
                        {
                            fields.Add(s);
                        }

                        if (deltaValues2 != deltaText2)
                        {
                            deltaText2 = deltaValues2;

                            SkipLine(ref yPos, ref numLines);
                            PrintRowCells(report.Data.SubGroup, row, group1XPosition, ref yPos, ref rect, myBrush, e, recordIndex, ref numLines, deltaText + deltaText2, fields);

                            SkipLine(ref yPos, ref numLines);
                            if (numLines <= 0)
                            {

                                return recordIndex++;

                            }

                            SkipLine(ref yPos, ref numLines);
                            e.Graphics.DrawLine(linePen, leftMargin + report.Data.Group.Indent, yPos - report.Settings.HeaderFont.Height, leftMargin + report.Data.Group.Indent, yPos + report.Settings.HeaderFont.Height / 2);
                            e.Graphics.DrawLine(linePen, leftMargin + report.Data.Group.Indent, yPos + report.Settings.HeaderFont.Height / 2, leftMargin + report.Data.SubGroup2.Indent, yPos + report.Settings.HeaderFont.Height / 2);
                            PrintColumns(report.Data.SubGroup2.Columns, group2XPosition, ref yPos, ref rect, myBrush, linePen, e);
                            SkipLine(ref yPos, ref numLines);

                        }

                    }


                    ///////////////////LEVEL 3 PRINTING///////////////////////////////
                    if (report.Data.SubGroup2.RowCellInfos.Count == 0)
                    {
                        Debug.WriteLine("CONTINUE: Increase record Index");
                        recordIndex++;
                        SkipLine(ref yPos, ref numLines);
                        continue;      //No Level 3: Skip Level three printing
                    }
                    else
                    {
                        Debug.WriteLine("Level3:" + deltaText + deltaText2);
                        PrintRowCells(report.Data.SubGroup2, row, group2XPosition, ref yPos, ref rect, myBrush, e, recordIndex, ref numLines, deltaText + deltaText2, fields);
                        //SkipLine(ref yPos,ref numLines);
                    }


                    SkipLine(ref yPos, ref numLines);
                    Debug.WriteLine("Increase record Index");
                    recordIndex++;


                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Report Error");
            }

            Debug.WriteLine("END Print Group Num Lines:" + numLines);

            return recordIndex;
        }

        #endregion

        #region Print General List Report
        private int PrintGeneralListReport(DataTable table, int numLines, int recordIndex, int yPos, PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            int leftMargin = e.MarginBounds.Left;
            int rightMargin = e.MarginBounds.Right;

            //Used for all painting. They are created here so that I don't have to
            //waste time creating them again in this procedure
            myBrush = new SolidBrush(report.Settings.RowSeparatorLine.Color);

            linePen.Width = (float)report.Settings.RowSeparatorLine.Thickness;


            //Initialize dummy rect for drawing text
            Rectangle rect = new Rectangle(0, 0, 0, 0);

            //Print the columns for this general list report
            PrintColumns(myBrush, linePen, rect, yPos, e);

            //Skip line after columns
            SkipLine(ref yPos, ref numLines);

            Debug.WriteLine("General List NumLines:" + numLines.ToString());

            int counter = 0;

            //Used if there are more than one line per row
            int maxLines = report.Data.ColumnCellCollection.GetMaxAmountLinesUsedForRow();

            int originalY = yPos;

            //Get the numbers of record in the dataview
            int end = table.DefaultView.Count;

            //Start 
            try
            {
                while (counter < numLines && recordIndex < end)
                {

                    //We take the records from the defaultview because the user can filter
                    //the table and only want the filtered row to print.
                    DataRow row = table.DefaultView[recordIndex].Row;

                    //Print Row Data
                    int x2 = leftMargin;
                    int tempX = 0;
                    int y = yPos;

                    //Color alternate rows
                    if (report.Settings.ColorAlternateRows && counter % 2 == 1)
                    {
                        myBrush.Color = report.Settings.AlternateRowColor;
                        e.Graphics.FillRectangle(myBrush, leftMargin, yPos, e.MarginBounds.Width, maxLines * report.Settings.HeaderFont.Height);
                    }



                    //Print rows directly under their corresponding columns
                    foreach (ColumnCell columnCell in this.report.Data.ColumnCellCollection)
                    {
                        tempX = x2;

                        foreach (RowCellInfo cellInfo in columnCell.RowCellInfoCollection)
                        {


                            if (row.IsNull(cellInfo.DatabaseField)) cellInfo.RowCell.Text = report.Settings.NullValue;   //No data to print, so replace it with a the null value specified

                            else
                            {
                                //A lookup table is specified
                                if (cellInfo.LookupTable != null)
                                {
                                    DataTable lookupTable = cellInfo.LookupTable;
                                    string key = String.Empty;
                                    try
                                    {
                                        key = row[cellInfo.DatabaseField].ToString();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Report Error, Key '" + cellInfo.DatabaseField + "' not found in main table\n\nDetails:\n" + ex.Message);
                                    }

                                    int rowCounter = 0;  //Count how many rows you have searched
                                    foreach (DataRow r in lookupTable.Rows)
                                    {
                                        if (r[cellInfo.LookupKeyColumn].ToString() == key)
                                        {
                                            string columnValue = String.Empty;
                                            foreach (string column in cellInfo.MappedColumns)
                                            {
                                                columnValue += r[column].ToString();
                                            }
                                            cellInfo.RowCell.Text = columnValue;
                                            break;
                                        }
                                        rowCounter++;
                                    }

                                    //If equal to the size of the row collection then no matching records were
                                    //found
                                    if (rowCounter == lookupTable.Rows.Count)
                                    {
                                        cellInfo.RowCell.Text = "No Match";
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        cellInfo.RowCell.Text = row[cellInfo.DatabaseField].ToString();
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("Column'" + cellInfo.DatabaseField + "' not found in main table\n\nDetails:\n" + ex.Message);
                                    }
                                }
                            }

                            //Configure Summaries for this row cell (if any)
                            if (cellInfo.FunctionType != FunctionType.None)
                            {
                                ConfigureFunction(cellInfo);
                            }

                            //Draw the cell data and description text(if any)

                            DrawCell(cellInfo.Text, tempX, y, ref rect, myBrush, e);
                            DrawCell(cellInfo.RowCell, tempX + cellInfo.Text.Width, y, ref rect, myBrush, e);

                            //Determine if this is the last row for this grouping
                            if (cellInfo.FunctionType != FunctionType.None)
                            {
                                if (IsLastRow(table, recordIndex + 1))
                                {
                                    //Print Totals
                                    PrintTotals(cellInfo, myBrush, tempX + cellInfo.RowCell.Width, yPos + report.Settings.HeaderFont.Height + 10, e);

                                    //Draw a line above and below the the totals
                                    if (cellInfo.PrintSummaryLine)
                                    {
                                        report.Settings.SummaryLinePen.Color = cellInfo.SummaryLine.Color;
                                        report.Settings.SummaryLinePen.Width = (float)cellInfo.SummaryLine.Thickness;
                                        g.DrawLine(report.Settings.SummaryLinePen, tempX + cellInfo.Text.Width, yPos + report.Settings.HeaderFont.Height + 5, tempX + columnCell.Width, yPos + report.Settings.HeaderFont.Height + 5);
                                        g.DrawLine(report.Settings.SummaryLinePen, tempX + cellInfo.Text.Width, yPos + report.Settings.HeaderFont.Height * 2 + 5, tempX + columnCell.Width, yPos + report.Settings.HeaderFont.Height * 2 + 5);
                                    }

                                    //Clear the collection that was used to stores all values calculated upon
                                    if (cellInfo.NumberCollection != null) cellInfo.NumberCollection.Clear();
                                }
                            }

                            //Draw the other cells in this column. A column can contain one or more
                            //database fields
                            if (columnCell.RowCellInfoPosition == RowCellInfoPosition.OneLine)
                                tempX += cellInfo.Text.Width + cellInfo.RowCell.Width;
                            else
                                y = y + report.Settings.HeaderFont.Height;

                        }

                        y = yPos;

                        x2 += columnCell.Width;
                        if (report.Settings.PrintTableGrid)
                        {
                            e.Graphics.DrawLine(linePen, x2, (int)yPos, x2, (int)yPos + (maxLines * report.Settings.HeaderFont.Height));
                        }

                    }

                    counter += maxLines;
                    yPos = yPos + (maxLines * report.Settings.HeaderFont.Height);

                    if (report.Settings.PrintRowSeparator)
                    {
                        linePen.Color = report.Settings.RowSeparatorLine.Color;
                        DrawRowSeparatorLine(report.Settings.RowSeparatorLine, (int)yPos, linePen, e);
                    }
                    recordIndex++;

                    //Outline Table with a line
                    if (report.Settings.OutlineTable && (counter == numLines || recordIndex == table.Rows.Count))
                    {
                        e.Graphics.DrawLine(linePen, leftMargin, originalY, leftMargin, yPos);
                        e.Graphics.DrawLine(linePen, rightMargin, originalY, rightMargin, yPos);
                        e.Graphics.DrawLine(linePen, leftMargin, yPos, rightMargin, yPos);
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Details:\n\n" + ex.Message, "Report Error");
            }

            return recordIndex;
        }

        #endregion

        #region Print
        private int Print(DataTable table, int recordIndex, PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;

            Bitmap image = new Bitmap(816, 1056);
            Graphics gr = Graphics.FromImage(image);

            gr.SmoothingMode = SmoothingMode.HighQuality;
            gr.InterpolationMode = InterpolationMode.HighQualityBilinear;
            gr.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            gr.DrawString("Page:" + currentPage.ToString(), report.Settings.SubHeaderFont, report.Settings.MyBrush, 10, 10);

            PictureBox dd = new PictureBox();
            dd.Image = image;


            display.PageImages.Add(dd);


            display.ShowPage(0);

            int yPos = e.MarginBounds.Top;  //Top margin position to start printing
            int leftMargin = e.MarginBounds.Left;
            int numLines = (e.MarginBounds.Height) / report.Settings.HeaderFont.Height;  //numlines changes if in Landscape mode

            numLines--;

            Debug.WriteLine("Number of Lines:" + numLines.ToString());
            Debug.WriteLine("Top Margins:" + yPos.ToString());
            Debug.WriteLine("Font Height:" + report.Settings.HeaderFont.Height);


            //Print report report.Settings.Header on first page of report
            if (recordIndex == 0 && report.Settings.PrintHeading == PrintHeading.OnFirstPage)
            {
                PrintHeader(ref yPos, ref numLines, e);
            }
            else if (report.Settings.PrintHeading == PrintHeading.OnAllPages)
            {
                //Print report report.Settings.Header on all pages of report
                PrintHeader(ref yPos, ref numLines, e);
            }

            //If this is a free form report then PrintFreeForm
            if (report.Settings.ReportType == ReportType.FreeForm)
            {
                return PrintFreeForm(table, numLines, recordIndex, yPos, e);
            }

            //No records to print
            if (table != null && table.DefaultView.Count == 0)
            {
                e.Graphics.DrawString("NO RECORDS", new Font(report.Settings.SubscriptFont, FontStyle.Bold), myBrush, leftMargin, yPos);
                e.HasMorePages = false;
                return 0;
            }

            Debug.WriteLine("Number of Lines:" + numLines.ToString());
            Debug.WriteLine("Top Margins:" + yPos.ToString());

            //Print date on report
            if (report.Settings.ReportDate != PrintReportDateLocation.None)
            {
                PrintDate(this.report.Settings.ReportDate, e);
                if (report.Settings.ReportDate == PrintReportDateLocation.LeftTop ||
                    report.Settings.ReportDate == PrintReportDateLocation.RightTop)

                    SkipLine(ref yPos, ref numLines);
            }

            //Print the total amount of records in this table
            if (report.Settings.PrintTotalRecords)
            {
                SizeF size = e.Graphics.MeasureString(report.Settings.TotalText + ":" + table.Rows.Count.ToString(), report.Settings.SubHeaderFont);
                g.DrawString(report.Settings.TotalText + ":" + table.Rows.Count.ToString(), report.Settings.SubHeaderFont, Brushes.Black, e.MarginBounds.Right - (int)size.Width, yPos);
            }

            //Print any text section for this report
            foreach (TextSection ts in report.Data.TextSections)
            {
                DrawTextSection(ts, leftMargin, yPos, ref rect, myBrush, e);
                SkipLine(ref yPos, ref numLines);
            }

            SkipLine(ref yPos, ref numLines);

            //Print Hierarchy Report
            if (report.Settings.ReportType == ReportType.Hierachy)
            {
                recordIndex = PrintGroup(table, numLines, recordIndex, ref yPos, e);
            }

            //Print General List Report
            else if (report.Settings.ReportType == ReportType.GeneralList)
            {
                recordIndex = PrintGeneralListReport(table, numLines, recordIndex, yPos, e);
            
            }

            if (report.Settings.PrintPageNumbers)
            {
                //Print page number at the bottom of the page
                g.DrawString("[ " + currentPage.ToString() + " ]", report.Settings.SubscriptFont, Brushes.Black, e.PageBounds.Width / 2, (float)e.MarginBounds.Bottom + report.Settings.HeaderFont.Height);
            }

            int end = table.DefaultView.Count;


            if (recordIndex >= end)
            {
                SkipLine(ref yPos, ref numLines);

                //Reset for group reports
                deltaText = String.Empty;
                deltaText2 = String.Empty;

                //Print Grand Totals
                PrintGrandTotals(myBrush, linePen, leftMargin, ref yPos, e);

                e.HasMorePages = false;

                //Reset variables
                recordIndex = 0;
                numPages = currentPage;

                AddPageButtons(numPages, image);

                currentPage = 1;

            }
            else
            {
                currentPage++;
                e.HasMorePages = true;
            }


            UpdateStatusbar();


            return recordIndex;
        }
        #endregion

        #endregion

        #region Helper Methods

        private void PrintRowCells(Group group, DataRow row, int position, ref int yPos, ref Rectangle rect, SolidBrush myBrush, PrintPageEventArgs e, int recordIndex, ref int numLines, string deltaText, StringCollection databaseFields)
        {

            //Debug.WriteLine("DeltaText:"+deltaText);
            //PrintStringCollection(databaseFields);

            Debug.WriteLine("PrintRowCell RecordIndex:" + recordIndex.ToString());

            foreach (RowCellInfo cellInfo in group.RowCellInfos)
            {
                cellInfo.RowCell.Text = row.IsNull(cellInfo.DatabaseField) ? report.Settings.NullValue : row[cellInfo.DatabaseField].ToString();//+"::"+numLines.ToString();

                ///////////CONFIGURE SUMMARIES
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    ConfigureFunction(cellInfo);
                }

                //Draw the cell
                DrawCell(cellInfo.Text, position, (int)yPos, ref rect, myBrush, e);
                position += cellInfo.Text.Width;
                DrawCell(cellInfo.RowCell, position, (int)yPos, ref rect, myBrush, e);


                //Determine if this is the last row for this grouping
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    //Debug.WriteLine("Function type for:"+cellInfo.RowCell.Text);
                    bool lastRow = false;

                    //Debug.WriteLine("Start Calling LastRow");
                    lastRow = IsLastRow(this.DataTable, recordIndex + 1, deltaText, databaseFields);
                    //Debug.WriteLine("finish Calling LastRow");

                    if (lastRow && !cellInfo.SuppressSummaryPrinting)
                    {
                        //Debug.WriteLine("Printing Function total");
                        //Skip a line

                        yPos += report.Settings.HeaderFont.Height;
                        //counter++;

                        //Print Totals
                        //  position + cellInfo.Text.Width


                        PrintTotals(cellInfo, myBrush, position + cellInfo.RowCell.Width, yPos, e);

                        //Draw a line below the the totals
                        if (cellInfo.PrintSummaryLine)
                        {
                            report.Settings.SummaryLinePen.Color = cellInfo.SummaryLine.Color;
                            report.Settings.SummaryLinePen.Width = (float)cellInfo.SummaryLine.Thickness;
                            e.Graphics.DrawLine(report.Settings.SummaryLinePen, position + cellInfo.Text.Width, yPos - 1, position + cellInfo.Text.Width + cellInfo.RowCell.Width - 5, yPos - 1);
                        }

                        yPos = yPos - report.Settings.HeaderFont.Height;

                        //Clear the collection that was used to stores all values calculated upon
                        if (cellInfo.NumberCollection != null) cellInfo.NumberCollection.Clear();
                    }
                    else
                    {
                        //Debug.WriteLine("Not Last row");
                    }
                }

                //Increase this variable in the case there might be more cells to draw
                position += cellInfo.RowCell.Width;
                ///////////END CONFIGURE SUMMARIES
            }
        }

        private void PrintColumns(ColumnCellCollection columns, int position, ref int yPos, ref Rectangle rect, SolidBrush myBrush, Pen linePen, PrintPageEventArgs e)
        {
            foreach (ColumnCell column in columns)
            {
                column.Height = report.Settings.HeaderFont.Height;
                DrawColumn(column, position, yPos, ref rect, myBrush, linePen, e);
                position += column.Width;
            }

        }

        private void PrintColumns(SolidBrush myBrush, Pen linePen, Rectangle rect, float yPos, PrintPageEventArgs e)
        {
            //Draw Columns from left margins
            int x = e.MarginBounds.Left;
            foreach (ColumnCell columnCell in this.report.Data.ColumnCellCollection)
            {
                //Draw the column
                columnCell.Height = report.Settings.HeaderFont.Height;
                DrawColumn(columnCell, x, (int)yPos, ref rect, myBrush, linePen, e);

                //Draw a rectangle around the column until the bottom of the page
                //if (report.Settings.PrintTableGrid)
                //DrawRectangle(x,(int)yPos,columnCell.Width,e.MarginBounds.Bottom-(int)yPos,linePen,e);

                x += columnCell.Width;
            }

        }

        private void SkipLine(ref int y, ref int numLines)
        {
            y = y + (report.Settings.HeaderFont.Height);
            numLines--;
        }

        private void SkipLine(ref float y, ref int counter)
        {
            y = y + (report.Settings.HeaderFont.Height);
            counter++;
        }

        private void PrintGrandTotals(SolidBrush myBrush, Pen linePen, int x, ref int y, PrintPageEventArgs e)
        {

            linePen.Width += 2;

            e.Graphics.DrawLine(linePen, e.MarginBounds.Left, y, e.PageBounds.Width - e.MarginBounds.Y, y);

            Rectangle rect = new Rectangle(0, 0, 0, 0);

            linePen.Width -= 2;

            decimal first = 0, second = 0;

            Stack s = new Stack(2);

            y = y + 5;

            foreach (RowCellInfo cellInfo in report.Data.Group.RowCellInfos)
            {
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    GrandSummaryCell gsc = cellInfo.GrandSummaryCell;
                    gsc.ColumnCell.Height = report.Settings.HeaderFont.Height;
                    gsc.RowCell.Height = report.Settings.HeaderFont.Height;

                    switch (cellInfo.FunctionType)
                    {
                        case FunctionType.Average:
                            e.Graphics.DrawString(cellInfo.AverageText + cellInfo.TotalNumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;

                        case FunctionType.Summary:

                            double sum = cellInfo.TotalNumberCollection.GetSum();
                            if (report.Settings.CalculatedField.IndexOf(cellInfo.DatabaseField) != -1)
                            {
                                s.Push(sum);
                            }

                            gsc.RowCell.Text = sum.ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                        case FunctionType.Maximum:
                            e.Graphics.DrawString(cellInfo.MaximumText + cellInfo.TotalNumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Minimum:
                            e.Graphics.DrawString(cellInfo.MinimumText + cellInfo.TotalNumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Count:
                            e.Graphics.DrawString(cellInfo.CountText + cellInfo.TotalNumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                    }

                    x += gsc.RowCell.Width + 10;
                    cellInfo.TotalNumberCollection.Clear();
                }

            }

            foreach (RowCellInfo cellInfo in report.Data.SubGroup.RowCellInfos)
            {
                if (cellInfo.FunctionType != FunctionType.None)
                {
                    GrandSummaryCell gsc = cellInfo.GrandSummaryCell;
                    gsc.ColumnCell.Height = report.Settings.HeaderFont.Height;
                    gsc.RowCell.Height = report.Settings.HeaderFont.Height;

                    switch (cellInfo.FunctionType)
                    {
                        case FunctionType.Average:
                            e.Graphics.DrawString(cellInfo.AverageText + cellInfo.TotalNumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Summary:

                            double sum = cellInfo.TotalNumberCollection.GetSum();

                            if (report.Settings.CalculatedField.IndexOf(cellInfo.DatabaseField) != -1)
                            {
                                s.Push(sum);
                            }

                            gsc.RowCell.Text = sum.ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                        case FunctionType.Maximum:
                            e.Graphics.DrawString(cellInfo.MaximumText + cellInfo.TotalNumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Minimum:
                            e.Graphics.DrawString(cellInfo.MinimumText + cellInfo.TotalNumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim()), report.Settings.SummaryLineFont, myBrush, x, y);
                            break;
                        case FunctionType.Count:

                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                    }
                    x += gsc.RowCell.Width + 10;
                    cellInfo.TotalNumberCollection.Clear();

                }

            }

            foreach (RowCellInfo cellInfo in report.Data.SubGroup2.RowCellInfos)
            {

                if (cellInfo.FunctionType != FunctionType.None)
                {
                    GrandSummaryCell gsc = cellInfo.GrandSummaryCell;
                    gsc.ColumnCell.Height = report.Settings.HeaderFont.Height;
                    gsc.RowCell.Height = report.Settings.HeaderFont.Height;

                    switch (cellInfo.FunctionType)
                    {
                        case FunctionType.Average:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetAverage().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                        case FunctionType.Summary:

                            double sum = cellInfo.TotalNumberCollection.GetSum();

                            if (report.Settings.CalculatedField.IndexOf(cellInfo.DatabaseField) != -1)
                            {
                                s.Push(sum);
                            }
                            gsc.RowCell.Text = sum.ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);

                            break;
                        case FunctionType.Maximum:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetMaximum().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                        case FunctionType.Minimum:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetMinimum().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                        case FunctionType.Count:
                            gsc.RowCell.Text = cellInfo.TotalNumberCollection.GetCount().ToString(cellInfo.SummaryFormatString.Trim());
                            DrawColumn(gsc.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                            DrawCell(gsc.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
                            break;
                    }
                    x += gsc.RowCell.Width + 10;
                    cellInfo.TotalNumberCollection.Clear();
                }
            }

            if (report.Settings.CalculatedField != String.Empty && s.Count > 0)
            {
                second = Convert.ToDecimal(s.Pop());
                first = Convert.ToDecimal(s.Pop());

                GrandSummaryCell c = new GrandSummaryCell();
                c.RowCell.Font = new Font(c.RowCell.Font, FontStyle.Bold);

                c.GrandSummaryText = "BALANCE DUE";
                c.RowCell.Text = (first - second).ToString("C");
                c.RowCell.Height = report.Settings.HeaderFont.Height;
                c.ColumnCell.Height = report.Settings.HeaderFont.Height;
                c.ColumnCell.BackgroundColor = Color.Red;
                DrawColumn(c.ColumnCell, x, y, ref rect, myBrush, linePen, e);
                DrawCell(c.RowCell, x, y + report.Settings.HeaderFont.Height, ref rect, myBrush, e);
            }
        }

        private bool ThumbnailCallback()
        {
            return false;

        }

        private void AddPageButtons(int numOfPages, Image image)
        {

            Image.GetThumbnailImageAbort thumbnailCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);

            Image tn = image.GetThumbnailImage(48, 48, thumbnailCallback, IntPtr.Zero);


            if (numOfPages <= 1)
            {
                pnlPage.Visible = false;
                return;

            }
            else
            {
                pnlPage.Visible = true;
     
            }

            PanelSuspendLayout();

            ClearPanelControls();

            int y = 8;
            for (int i = 1; i <= numOfPages; i++)
            {
                ThemedButton btnPage = new ThemedButton();
                btnPage.Size = new Size(56, 72);
                //  btnPage.Image = btnSample.Image;
                btnPage.Image = btnSample.Image; 
                btnPage.Location = new Point(x, y);
                btnPage.Text = "Page: " + i.ToString();
                btnPage.Tag = i;
                btnPage.TextAlign = ContentAlignment.TopCenter;
                btnPage.ImageAlign = ContentAlignment.BottomCenter;
                btnPage.FlatStyle = FlatStyle.Flat;
                btnPage.Cursor = Cursors.Hand;
                btnPage.Font = btnSample.Font;

                btnPage.Click += new EventHandler(PageButtons_Click);

                y += 80;
                this.tt.SetToolTip(btnPage, "Page " + i.ToString());

                //pnlPage.Controls.Add(btnPage);
                AddButtonToPanel1(btnPage);

            }

            PanelResumeLayout();
            
        }

        private delegate void AddButtonToPanel(ThemedButton tb);
        private delegate void GeneralDelegate();

        private void AddButtonToPanel1(ThemedButton tb)
        {
            if (pnlPage.InvokeRequired)
            {
                AddButtonToPanel d = new AddButtonToPanel(AddButtonToPanel1);
                this.Invoke(d, new object[] { tb });
            }
            else

                pnlPage.Controls.Add(tb);

        }


        private void ClearPanelControls()
        {
            if (pnlPage.InvokeRequired)
            {
                GeneralDelegate d = new GeneralDelegate(ClearPanelControls);
                this.Invoke(d);
            }
            else

                pnlPage.Controls.Clear();

        }

        private void PanelSuspendLayout()
        {
            if (pnlPage.InvokeRequired)
            {
                GeneralDelegate d = new GeneralDelegate(PanelSuspendLayout);
                this.Invoke(d);
            }
            else

                pnlPage.SuspendLayout();

        }

        private void PanelResumeLayout()
        {
            if (pnlPage.InvokeRequired)
            {
                GeneralDelegate d = new GeneralDelegate(PanelResumeLayout);
                this.Invoke(d);
            }
            else

                pnlPage.ResumeLayout();

        }






        private bool IsLastRow(DataTable table, int recordIndex, string data, StringCollection databaseFields)
        {

            Debug.WriteLine("IsLastRow:RecordIndex:" + recordIndex.ToString());
            int end = 0;
            IEnumerator m = table.DefaultView.GetEnumerator();

            while (m.MoveNext())
            {
                end++;
            }

            if (recordIndex >= end)
            {
                //If the table has no more records return true
                Debug.WriteLine("IsLastRow No More records Return true");
                return true;
            }

            DataRow row = table.DefaultView[recordIndex].Row;

            string c = String.Empty;

            foreach (string s in databaseFields)
            {
                c += row[s].ToString();
            }

            Debug.WriteLine("IsLastRow:" + c + ":" + data);
            if (c != data)
            {
                Debug.WriteLine("IsLastRow NOT Equal Return true");
                return true;
            }
            else
            {
                Debug.WriteLine("IsLastRow Equal Return false");
                return false;
            }


        }

        private bool IsLastRow(DataTable table, int index)
        {

            int end = 0;
            IEnumerator m = table.DefaultView.GetEnumerator();

            while (m.MoveNext())
            {
                end++;
            }

            if (index == end)
            {

                return true;
            }
            else
                return false;

            //			if (index==table.Rows.Count)
            //			{
            //
            //				return true;
            //			}else
            //				return false;

        }

        private void DrawRectangle(ReportRectangle rr, Pen pen, Graphics g)
        {
            RectangleF r = rr.RectangleF;
            pen.Width = (float)rr.Thickness / 96f;
            pen.Color = rr.Color;
            g.DrawRectangle(pen, r.X * CENTIMETER_TO_INCH, r.Y * CENTIMETER_TO_INCH, r.Width * CENTIMETER_TO_INCH, r.Height * CENTIMETER_TO_INCH);
        }

        private void PrintDate(PrintReportDateLocation location, PrintPageEventArgs e)
        {

            switch (location)
            {
                case PrintReportDateLocation.LeftTop:
                    {
                        e.Graphics.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top);
                        break;
                    }
                case PrintReportDateLocation.LeftBottom:
                    {
                        e.Graphics.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Bottom);
                        break;
                    }
                case PrintReportDateLocation.RightTop:
                    {
                        SizeF size = e.Graphics.MeasureString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont);

                        e.Graphics.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, e.MarginBounds.Right - (int)size.Width, e.MarginBounds.Top);
                        break;
                    }

                case PrintReportDateLocation.RightBottom:
                    {
                        SizeF size = e.Graphics.MeasureString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont);
                        e.Graphics.DrawString(DateTime.Now.ToShortDateString(), report.Settings.SubHeaderFont, Brushes.Black, e.MarginBounds.Right - (int)size.Width, e.MarginBounds.Bottom);
                        break;
                    }

            }

        }

        private void DrawRowSeparatorLine(LineInfo lineInfo, int y, Pen pen, PrintPageEventArgs e)
        {
            e.Graphics.DrawLine(pen, e.MarginBounds.X, y, e.MarginBounds.Right, y);
        }

        private void DrawLine(LineInfo lineInfo, Pen pen, PrintPageEventArgs e)
        {
            pen.Width = (float)lineInfo.Thickness / 96f;
            pen.Color = lineInfo.Color;

            e.Graphics.DrawLine(pen, lineInfo.X * CENTIMETER_TO_INCH, lineInfo.Y * CENTIMETER_TO_INCH, lineInfo.X1 * CENTIMETER_TO_INCH, lineInfo.Y1 * CENTIMETER_TO_INCH);
        }



        private void DrawCell(RowCell cell, int x, int y, ref Rectangle rect, SolidBrush brush, PrintPageEventArgs e)
        {
            //Make sure that there is a value to print
            if (cell.Text.Trim() == String.Empty && cell.DontPrintIfBlank) return;

            if (cell.Width == 0) return;

            if (cell.ExtendToMargin)
                rect.Width = e.MarginBounds.Right - x;
            else
                rect.Width = cell.Width;

            rect.Height = report.Settings.HeaderFont.Height;
            rect.X = x;
            rect.Y = y;


            brush.Color = cell.BackgroundColor;

            if (cell.BackgroundColor != Color.White)
            {
                e.Graphics.FillRectangle(brush, rect);

            }

            brush.Color = cell.ForeColor;

            //Format the cell data
            defaultStringFormat.Alignment = (StringAlignment)((int)cell.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)cell.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = cell.CellFormat.FormatFlags;
            defaultStringFormat.Trimming = (StringTrimming)((int)cell.CellFormat.Trimming);

            if (cell.FormatString != String.Empty && cell.Text != report.Settings.NullValue)
            {
                string formattedString = String.Empty;
                switch (cell.DataType)
                {
                    case DataType.Int32:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", Int32.Parse(cell.Text));
                        break;
                    case DataType.Double:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", Double.Parse(cell.Text));
                        break;
                    case DataType.DateTime:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", DateTime.Parse(cell.Text));
                        break;

                    case DataType.String:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", cell.Text);
                        break;
                }
                cell.Text = formattedString;
            }

            if (cell.Image != null)
            {
                e.Graphics.DrawImage(cell.Image, rect.X, rect.Y, cell.Image.Width, cell.Image.Height);

            }

            if (cell.LeftPadding > 0)
            {
                cell.Text = PadText(cell.Text.Trim(), cell.PaddingCharacter, cell.LeftPadding);
            }

            if (cell.Outline)
                e.Graphics.DrawRectangle(Pens.Black, rect);

            e.Graphics.DrawString(" " + cell.Text, cell.Font, brush, rect, defaultStringFormat);
        }

        private void DrawCell(RowCell cell, float x, float y, ref RectangleF rect, SolidBrush brush, Graphics g)
        {
            //Make sure that there is a value to print
            if (cell.Text.Trim() == String.Empty && cell.DontPrintIfBlank) return;
            if (cell.Width == 0) return;

            rect.Width = cell.Width * CENTIMETER_TO_INCH;
            rect.Height = report.Settings.HeaderFont.GetHeight(g);
            rect.X = x;
            rect.Y = y;


            brush.Color = cell.BackgroundColor;

            if (cell.BackgroundColor != Color.White)
            {
                g.FillRectangle(brush, rect);
            }

            brush.Color = cell.ForeColor;

            //Format the cell data
            defaultStringFormat.Alignment = (StringAlignment)((int)cell.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)cell.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = cell.CellFormat.FormatFlags;
            defaultStringFormat.Trimming = (StringTrimming)((int)cell.CellFormat.Trimming);

            if (cell.FormatString != String.Empty && cell.Text != report.Settings.NullValue)
            {
                string formattedString = String.Empty;
                switch (cell.DataType)
                {
                    case DataType.Int32:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", Int32.Parse(cell.Text));
                        break;
                    case DataType.Double:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", Double.Parse(cell.Text));
                        break;
                    case DataType.DateTime:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", DateTime.Parse(cell.Text));
                        break;

                    case DataType.String:
                        formattedString = String.Format("{0:" + cell.FormatString.Trim() + "}", cell.Text);
                        break;
                }
                cell.Text = formattedString;
            }


            if (cell.Image != null)
            {
                g.DrawImage(cell.Image, rect.X, rect.Y, cell.Image.Width, cell.Image.Height);
            }

            if (cell.LeftPadding > 0)
            {
                cell.Text = PadText(cell.Text.Trim(), cell.PaddingCharacter, cell.LeftPadding);

            }

            if (cell.Outline)
            {
                Pen p = new Pen(brush, 1 / 96);
                g.DrawRectangle(p, rect.X, rect.Y, rect.Width, rect.Height);
            }

            g.DrawString(" " + cell.Text, cell.Font, brush, rect, defaultStringFormat);
        }

        private string PadText(string text, char paddingChar, int count)
        {
            if (count <= 0) return text;
            else
                return new String(paddingChar, count) + text;

        }

        private void DrawColumn(ColumnCell columnCell, int x, int y, ref Rectangle rect, SolidBrush brush, Pen linePen, PrintPageEventArgs e)
        {
            //Check if to draw this column all the way to the end margin
            if (columnCell.ExtendToMargin)
            {
                columnCell.Width = e.MarginBounds.Right - x;
                rect.Width = e.MarginBounds.Right - x;
            }
            else
                rect.Width = columnCell.Width;

            rect.Height = columnCell.Height;
            rect.X = x;
            rect.Y = y;

            //Draw column background
            brush.Color = columnCell.BackgroundColor;
            if (columnCell.BackgroundColor != Color.White)
                e.Graphics.FillRectangle(brush, rect);


            //Print a separator line at the end of the column
            if (columnCell.PrintSeparator)
                e.Graphics.DrawRectangle(Pens.Black, rect.X, rect.Y, rect.Width, rect.Height);

            //Align the text in the columns
            defaultStringFormat.Alignment = (StringAlignment)((int)columnCell.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)columnCell.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = (StringFormatFlags)((int)columnCell.CellFormat.FormatFlags);
            defaultStringFormat.Trimming = (StringTrimming)((int)columnCell.CellFormat.Trimming);

            brush.Color = columnCell.ForeColor;
            //Draw the column
            e.Graphics.DrawString(" " + columnCell.Text, columnCell.Font, brush, rect, defaultStringFormat);

            if (columnCell.OutlineColumn)
            {
                linePen.Color = report.Settings.RowSeparatorLine.Color;
                e.Graphics.DrawRectangle(linePen, rect);
            }

        }

        private void DrawTextSection(TextSection textSection, int x, int y, ref Rectangle rect, SolidBrush brush, PrintPageEventArgs e)
        {
            //Check if to draw this column all the way to the end margin
            if (textSection.ExtendToMargin)
            {
                textSection.Width = e.MarginBounds.Right - x;
                rect.Width = e.MarginBounds.Right - x;
            }
            else
                rect.Width = textSection.Width;

            if (textSection.Height == 0)
                textSection.Height = report.Settings.HeaderFont.Height;

            rect.Height = textSection.Height;
            rect.X = x;
            rect.Y = y;

            //Draw background color
            brush.Color = textSection.BackgroundColor;
            e.Graphics.FillRectangle(brush, rect);

            //Align the text in the columns
            defaultStringFormat.Alignment = (StringAlignment)((int)textSection.CellFormat.Alignment);
            defaultStringFormat.LineAlignment = (StringAlignment)((int)textSection.CellFormat.LineAlignment);
            defaultStringFormat.FormatFlags = (StringFormatFlags)((int)textSection.CellFormat.FormatFlags);
            defaultStringFormat.Trimming = (StringTrimming)((int)textSection.CellFormat.Trimming);

            brush.Color = textSection.ForeColor;

            //Draw the column
            e.Graphics.DrawString(textSection.Text, textSection.Font, brush, rect, defaultStringFormat);

            if (textSection.Outline)
            {
                e.Graphics.DrawRectangle(Pens.Black, rect);
            }
        }

        #endregion

        private void cmStrip_Opening(object sender, CancelEventArgs e)
        {
            if (currentTable == null || currentTable.Rows.Count <= 0)
            {
                mnNextPage.Enabled = false;
                mnPreviousPage.Enabled = false;
                mnPrint.Enabled = false;
                mnZoom.Enabled = false;
                mnMultiplePages.Enabled = false;

            }
            else
            {
                mnNextPage.Enabled = true;
                mnPreviousPage.Enabled = true;
                mnPrint.Enabled = true;
                mnZoom.Enabled = true;
                mnMultiplePages.Enabled = true;
            }

        }

        #endregion

        private void ZoomItemsClicked(object sender, EventArgs e)
        {
            if (sender == mnAuto)
            {
                pp.AutoZoom = true;
                cbxZoom.SelectedIndex = 0;
            }
            else if (sender == mn500)
            {


                cbxZoom.SelectedIndex = 1;
            }
            else if (sender == mn200)
            {

                cbxZoom.SelectedIndex = 2;
            }
            else if (sender == mn150)
            {

                cbxZoom.SelectedIndex = 3;
            }
            else if (sender == mn100)
            {
                cbxZoom.SelectedIndex = 4;
            }
            else if (sender == mn90)
            {

                cbxZoom.SelectedIndex = 5;
            }
            else if (sender == mn80)
            {

                cbxZoom.SelectedIndex = 6;
            }
            else if (sender == mn75)
            {

                cbxZoom.SelectedIndex = 7;
            }
            else if (sender == mn70)
            {

                cbxZoom.SelectedIndex = 8;
            }
            else if (sender == mn60)
            {

                cbxZoom.SelectedIndex = 9;
            }

            else if (sender == mn50)
            {

                cbxZoom.SelectedIndex = 10;
            }
            else if (sender == mn40)
            {

                cbxZoom.SelectedIndex = 11;
            }
            else if (sender == mn30)
            {

                cbxZoom.SelectedIndex = 12;
            }

            UpdateStatusbar();

        }

        private void MultiplyItemsClicked(object sender, EventArgs e)
        {
            if (sender == mn1x1)
            {
                neRows.Value = 1;
                neColumns.Value = 1;
            }
            else if (sender == mn1x2)
            {
                neRows.Value = 1;
                neColumns.Value = 2;
            }
            else if (sender == mn1x3)
            {
                neRows.Value = 1;
                neColumns.Value = 3;
            }
            else if (sender == mn2x1)
            {
                neRows.Value = 2;
                neColumns.Value = 1;
            }
            else if (sender == mn2x2)
            {
                neRows.Value = 2;
                neColumns.Value = 2;
            }

            else if (sender == mn2x3)
            {
                neRows.Value = 2;
                neColumns.Value = 3;
            }

            UpdateStatusbar();
        }

        private void cmStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {

            ToolStripItem clickedItem = e.ClickedItem;


            if (clickedItem == mnNextPage)
            {

                NextPage();
            }
            else if (clickedItem == mnPreviousPage)
            {

                PreviousPage();

            }
            else if (clickedItem == mnPrint)
            {
                Print();
            }
            else if (clickedItem == mnFilter)
            {
                btnFilter_Click(null, null);

            }

            UpdateStatusbar();

        }

        private void btnTablePicker_Click(object sender, EventArgs e)
        {
            TablePicker tp = new TablePicker();
            tp.Location = this.PointToScreen(new Point(0, 0));
            tp.Top += btnTablePicker.Top + btnTablePicker.Size.Height;
            tp.Left += btnTablePicker.Left;
            tp.Show();
            while (tp.Visible)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(0);
            }
            if (!tp.Cancel)
            {
                neColumns.Value = tp.SelectedColumns;
                neRows.Value = tp.SelectedRows;
            }

        }

        private void p_Paint(object sender, PaintEventArgs e)
        {


        }

        private void button1_Click(object sender, EventArgs e)
        {

            //Graphics g = p.CreateGraphics();

            //g.DrawString(g.ToString(), new Font("Times New Arial", 14.75f), Brushes.Black, 2, 2);


            //Bitmap d = new Bitmap(816, 1056);


            //Graphics g1 = Graphics.FromImage(d);
            //g1.SmoothingMode = SmoothingMode.AntiAlias;

            //g1.SmoothingMode = SmoothingMode.HighQuality;
            //g1.InterpolationMode = InterpolationMode.HighQualityBilinear;
            //g1.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            //g1.DrawString(g.ToString(), new Font("Times New Arial", 14.75f), Brushes.Black, 2, 2);

            //// Graphics g = p.CreateGraphics();

            //pb.Image = d;



            //  Graphics g1 = p2.CreateGraphics();
            // g1.DrawString("hello", report.Settings.HeaderFont, report.Settings.MyBrush, 2, 2);

        }

        private void StarReport_Resize(object sender, EventArgs e)
        {
            Invalidate();
            display.Invalidate();
        }

        private void btnPrintPreview_Click(object sender, EventArgs e)
        {
            printPreview.Document = document;
            printPreview.ShowDialog();
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
          
        }

        private void pnlPage_Click(object sender, EventArgs e)
        {
           
        }









    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

FatCatProgrammer
Software Developer (Senior) Finance Industry
United States United States
Currently pursuing 'Programming Nirvana' (The ineffable ultimate in which one has attained disinterested wisdom and compassion as it relates to programming)

Respected Technologies
1. Confusor (https://confuser.codeplex.com/)
2. Power Threading (http://www.wintellect.com/Resources/visit-the-power-threading-library)
3. EDI Parsers (http://www.rdpcrystal.com)


Acknowledgements:

Microsoft Certified Technologist for WPF and .Net 3.5 (MCTS)
Microsoft Certified Technologist for WCF and .Net 3.5 (MCTS)
Microsoft Certified Application Developer for .Net (MCAD)
Microsoft Certified Systems Engineer (MCSE)
Microsoft Certified Professional (MCP)

Sun Certified Developer for Java 2 Platform (SCD)
Sun Certified Programmer for Java 2 Platform (SCP)
Sun Certified Web Component Developer (SCWCD)

CompTIA A+ Certified Professional

Registered Business School Teacher for Computer Programming and Computer Applications (2004)
(University of the State of New York Education Department)

Graduated from University At Stony Brook

You may also be interested in...

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.180621.3 | Last Updated 25 Jan 2013
Article Copyright 2012 by FatCatProgrammer
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid