Problema: come implementare in un form e  in maniera corretta un grafico e visualizzarlo su un report creato con crystal report.

Soluzione: usiamo zedgraph.

Il problema con zedgraph http://zedgraph.sourceforge.net/ è che la documentazione non è moltissima e occorre usare un pò di fantasia per poter svolgere correttamente i compiti assegnati per casa. Metto quindi un pò di pseudo-codice che consente di creare un grafico e poi metterlo su crystal report: 

 

using System;

using System.Drawing;

using System.Collections;

using System.ComponentModel;

using System.Windows.Forms;

using System.Data;

using ZedGraph;

using CrystalDecisions.CrystalReports.Engine;

using CrystalDecisions.Shared;

 

 

namespace WindowsApplication2

{

      ///

      /// Summary description for Form1.

      ///

      public class Form1 : System.Windows.Forms.Form

      {

     

            private ZedGraph.ZedGraphControl zedGraphControl1;

            ///

            /// Required designer variable.

            ///

            private System.ComponentModel.Container components = null;

 

            public Form1()

            {

                  //

                  // Required for Windows Form Designer support

                  //

                  InitializeComponent();

            }

 

            ///

            /// Clean up any resources being used.

            ///

            protected override void Dispose( bool disposing )

            {

                  if( disposing )

                  {

                        if (components != null)

                        {

                             components.Dispose();

                        }

                  }

                  base.Dispose( disposing );

            }

 

            #region Windows Form Designer generated code

            ///

            /// Required method for Designer support - do not modify

            /// the contents of this method with the code editor.

            ///

            private void InitializeComponent()

            {

                  this.zedGraphControl1 = new ZedGraph.ZedGraphControl();

                  this.SuspendLayout();

                  //

                  // zedGraphControl1

                  //

                  this.zedGraphControl1.IsEnableHPan = true;

                  this.zedGraphControl1.IsEnableVPan = true;

                  this.zedGraphControl1.IsEnableZoom = true;

                  this.zedGraphControl1.IsScrollY2 = false;

                  this.zedGraphControl1.IsShowContextMenu = true;

                  this.zedGraphControl1.IsShowHScrollBar = false;

                  this.zedGraphControl1.IsShowPointValues = false;

                  this.zedGraphControl1.IsShowVScrollBar = false;

                  this.zedGraphControl1.IsZoomOnMouseCenter = false;

                  this.zedGraphControl1.Location = new System.Drawing.Point(0, 0);

                  this.zedGraphControl1.Name = "zedGraphControl1";

                  this.zedGraphControl1.PanButtons = System.Windows.Forms.MouseButtons.Left;

                  this.zedGraphControl1.PanButtons2 = System.Windows.Forms.MouseButtons.Middle;

                  this.zedGraphControl1.PanModifierKeys2 = System.Windows.Forms.Keys.None;

                  this.zedGraphControl1.PointDateFormat = "g";

                  this.zedGraphControl1.PointValueFormat = "G";

                  this.zedGraphControl1.ScrollMaxX = 0;

                  this.zedGraphControl1.ScrollMaxY = 0;

                  this.zedGraphControl1.ScrollMaxY2 = 0;

                  this.zedGraphControl1.ScrollMinX = 0;

                  this.zedGraphControl1.ScrollMinY = 0;

                  this.zedGraphControl1.ScrollMinY2 = 0;

                  this.zedGraphControl1.TabIndex = 0;

                  this.zedGraphControl1.ZoomButtons = System.Windows.Forms.MouseButtons.Left;

                  this.zedGraphControl1.ZoomButtons2 = System.Windows.Forms.MouseButtons.None;

                  this.zedGraphControl1.ZoomModifierKeys = System.Windows.Forms.Keys.None;

                  this.zedGraphControl1.ZoomModifierKeys2 = System.Windows.Forms.Keys.None;

                  this.zedGraphControl1.ZoomStepFraction = 0.1;

                  this.zedGraphControl1.Click += new System.EventHandler(this.zedGraphControl1_Click);

                  //

                  // Form1

                  //

                  this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

                  this.ClientSize = new System.Drawing.Size(680, 414);

                  this.Controls.Add(this.zedGraphControl1);

                  this.Name = "Form1";

                  this.Text = "Form1";

                  this.Load += new System.EventHandler(this.Form1_Load);

                  this.ResumeLayout(false);

 

            }

            #endregion

 

            ///

            /// The main entry point for the application.

            ///

            [STAThread]

            static void Main()

            {

                  Application.Run( new Form1() );

            }

 

            private void Form1_Load( object sender, System.EventArgs e )

            {

                  CreaGrafico();

            }

 

            private void zedGraphControl1_Click(object sender, System.EventArgs e)

            {

                  AnteprimaGrafico();

            }

 

            protected void AnteprimaGrafico(){

                  if (System.IO.File.Exists("c:\\grafico.Png"))

 

                        System.IO.File.Delete("c:\\grafico.Png");

 

                  zedGraphControlMain.GraphPane.Image.Save (

 

                        "c:\\grafico.Png");

 

                  System.IO.FileStream fs = System.IO.File.OpenRead("c:\\grafico.Png");

 

                  byte[] data = new byte[fs.Length];

 

                  fs.Read(data, 0, data.Length);

 

                  fs.Close();

 

 

                  System.Data.DataTable dt = new System.Data.DataTable("immagine_grafico");

 

                  dt.Columns.Add("immagine_grafico", data.GetType());

 

                  ds.Tables.Add(dt);

 

                  System.Data.DataRow dr = ds.Tables[0].NewRow();

 

                  dr[0] = data;

 

                  ds.Tables[0].Rows.InsertAt(dr,0);

 

                  ds.WriteXmlSchema("..\\..\\xsd\\rptGrafico.xsd");

 

 

 

                  rpt = new ReportDocument();

 

                  rpt.Load("..\\..\\Report\\rptGrafico.rpt", CrystalDecisions.Shared.OpenReportMethod.OpenReportByTempCopy);

 

 

                  rpt.SetDataSource(this.ds);

 

                  rpt.Refresh();

 

 

                  FormReportViewer frmrpt = new FormReportViewer(rpt);

 

                  frmrpt.MdiParent = this.MdiParent;

 

                  frmrpt.Show();

 

 

            }

 

            protected void CreaGrafico()

            {

                 

                  zedGraphControl1.IsShowPointValues = true;

                  zedGraphControl1.GraphPane.Title = "Test Case for C#";

                  double[] x = new double[100];

                  double[] y = new double[100];

double[] z = new double[100];

                  int   i;

                  for ( i=0; i<100; i++ )

                  {

                        x[i] = (double) i / 100.0 * Math.PI * 2.0;

                        y[i] = Math.Sin( x[i] );

                        z[i] = Math.Cos( x[i] );

                  }

                  zedGraphControl1.GraphPane.AddCurve( "Sine Wave", x, y, Color.Red, SymbolType.Square );

                  zedGraphControl1.GraphPane.AddCurve( "Sine Wave", x, z, Color.Blue, SymbolType.Star );

                  zedGraphControl1.AxisChange();

                  zedGraphControl1.Invalidate();

           

                 

            }

 

     }

 

OK OK non sono stato chiarissimo causa fretta nel copia incolla necessita qualche spiegazione. 

 

Nel metodo creagrafico occorre chiamare prima di tutto il metodo

zedGraphControl1.GraphPane.CurveList.Clear();

altrimenti se viene richiamato, il metodo, duplica le colonne perchè aggiunge due volte i valori (cosa questa che mi ha fatto perdere parecchio tempo). Inoltre il metodo di salvare il file su disco e poi caricarlo su un dataset non è molto efficiente, occorrerebbe (e dio sia lodato per sourceforge per il codice sorgente) aggiungere/implementare qualche metodo dentro la classe ZedGraphControl. Tuttavia funziona (e se funziona non è poi così stupido) ed è anche molto veloce. Inoltre si possono scegliere fra vari tipi di grafico e nel sito è possibile vedere altri sorgenti.

In effetti il bello è che il costo è praticamente zero anche se uno deve sbattersi a cercare le soluzioni. Giudizio finale positivo per cui spero che sarà utile a qualcuno.

Resto in attesa di Vs. commenti e/o suggerimenti.

zero

 

 

posted on lunedì 2 gennaio 2006 19:03 |

Comments

Gravatar
# re: Grafici a buon prezzo
Posted by Hughes
on 19/03/2008 17:14
Ottimo articolo

Anche io stavo perdendo molto tempo per via della duplicazione delle curve prima di leggere questo articolo, non capivo come utilizzare il metodo .clear() per le curve, utilizzavo ClearAll che invece non mi funziona correttamente.
Gravatar
# picture of race car driver
on 25/10/2010 20:37
| &lt;a href=&quot;http://xn--gunds-zua.dk/tfzhYWgpd/&quot; &gt;glouster avenue picture&lt;/a&gt;
Gravatar
# re: Grafici a buon prezzo
Posted by gondes
on 27/10/2015 00:02
Wisata arung jeram di kota wisata batu rafting malang rafting murah Wisata paling populer di malang yang wajib dikunjungi wisata di malang Sungai yang digunakan untuk arung jeram di pujon rafting pujon rafting batu Paket wisata murah bromo tour dan rafting di malang bromo tour murah gunung bromo tour dan mencoba wisata arung jeram di malang bromo tour Objek wisata pantai terkenal di malang selatan wisata pantai di malang Pesona keindahan panorama sunrise di pantai goa cina malang pantai goa cina malang Objek wisata kasembon rafting arung jeram di batu kota malang kasembon rafting batu Mengarungi sungai terjernih di kasembon rafting malang rafting di kasembon Paket wisata murah tour gunung bromo dan kawah ijen wisata gunung bromo Paket wisata murah meriah ke gunung bromo dan kawah ijen banyuwangi bromo dan kawah ijen Travel dari kota surabaya ke malang murah muriah travel ke kota malang Museum rokok yaitu house of sampoerna di surabaya museum house of sampoerna Objek wisata terbaik museum rokok di surabaya museum rokok
Gravatar
# re: Grafici a buon prezzo
Posted by jordan
on 27/10/2015 00:08
travel murah di kota wisata malang yang terpercaya baca info disini sewa mobil jenis elf terbaik dan murah rental sewa mobil elf membuka bisnis baru sewa menyewa mobil di malang tips disini cara mengiklankan bisnis rental mobil di malang informasi lengkap rent car paling murah di kota malang detail info disini tempat perusahaan sewa mobil terbaik dan murah di malang kota detail lengkap disini alamat rental mobil tanpa driver kunjungi website informasi tempat rental mobil di malang kota info selengkapnya disini daftar alamat perusahaan rental mobil di batu kota malang baca info disini peluang bisnis persewaan mobil di malang batu jasa sewa mobil murah tips untuk memilih sewa mobil terpercaya di malang detail infonya disini
Gravatar
# Sorbics
Posted by Wainciah
on 21/07/2018 02:02
azan tefou
rise and grind meaning
what happened to kash biermann
lookliketv
Gravatar
# byclice
Posted by Homieks
on 21/07/2018 03:33
josh doctson
shalom brune-franklin
liam payne net worth
condy sue salling
Gravatar
# reils
Posted by Ideamb
on 05/09/2018 09:25
business plan writing services
essay help
read book online
write my essay
Gravatar
# Kilky
Posted by Roumult
on 11/09/2018 07:33
Comments have been closed on this topic.