2015-09-03 6 views
0

Мне нужно нарисовать график на C# ZedGraph в VS2013. Я создал проект приложения windowns и добавил Form1.cs в качестве файла формы win. Но, когда я запускал код, была создана только пустая форма, но графика не было. В режиме отладки я обнаружил, что Form1_Load() не выполняется. Зачем ?Form1_Load() не выполняется для построения графика

Это код C#.

using System.Windows.Forms; 
using ZedGraph; 
namespace zedgraph_test 
{ 
    public partial class Form1 : Form 
    { 
    public Form1() 
    { 
     InitializeComponent(); 
    } 
    // it is not executed. 
    private void Form1_Load(object sender, EventArgs e) 
    { 
     Console.WriteLine("Form1_Load is called"); 
     ZedGraph.ZedGraphControl zg1 = new ZedGraphControl(); 
     CreateChart(zg1); 
    } 
    // definition of CreateChart 
    ... 
} 

Любая помощь будет оценена по достоинству.

UPDATE

Я попробовал решение, но я только получил пустую форму, и никакие графики не отображаются в форме.

Это код From1.cs.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using ZedGraph; 
namespace zedgraph_test1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
     InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
     Console.WriteLine("Form1_Load is called"); 
     ZedGraph.ZedGraphControl zg1 = new ZedGraphControl(); 
     CreateChart(zg1); 
     SetSize(); 
     } 

     private void Form1_Resize(object sender, EventArgs e) 
     { 
     SetSize(); 
     } 

     private void SetSize() 
     { 
     zg1.Location = new Point(10, 10); 
     // Leave a small margin around the outside of the control 
     zg1.Size = new Size(this.ClientRectangle.Width - 20, this.ClientRectangle.Height - 20); 
     } 


     // Call this method from the Form_Load method, passing your ZedGraphControl 
    public static void CreateChart(ZedGraphControl zgc) 
    { 
     GraphPane myPane = zgc.GraphPane; 

     // Set the title and axis labels 
     myPane.Title.Text = "Vertical Bars with Value Labels Above Each Bar"; 
     myPane.XAxis.Title.Text = "Position Number"; 
     myPane.YAxis.Title.Text = "Some Random Thing"; 

     PointPairList list = new PointPairList(); 
     PointPairList list2 = new PointPairList(); 
     PointPairList list3 = new PointPairList(); 
     Random rand = new Random(); 

     // Generate random data for three curves 
     for (int i = 0; i < 5; i++) 
     { 
      double x = (double)i; 
      double y = rand.NextDouble() * 1000; 
      double y2 = rand.NextDouble() * 1000; 
      double y3 = rand.NextDouble() * 1000; 
      list.Add(x, y); 
      list2.Add(x, y2); 
      list3.Add(x, y3); 
     } 

     // create the curves 
     BarItem myCurve = myPane.AddBar("curve 1", list, Color.Blue); 
     BarItem myCurve2 = myPane.AddBar("curve 2", list2, Color.Red); 
     BarItem myCurve3 = myPane.AddBar("curve 3", list3, Color.Green); 

     // Fill the axis background with a color gradient 
     myPane.Chart.Fill = new Fill(Color.White, 
      Color.FromArgb(255, 255, 166), 45.0F); 

     zgc.AxisChange(); 

     // expand the range of the Y axis slightly to accommodate the labels 
     myPane.YAxis.Scale.Max += myPane.YAxis.Scale.MajorStep; 

     // Create TextObj's to provide labels for each bar 
     BarItem.CreateBarLabels(myPane, false, "f0"); 
     //Console.ReadLine(); 
    } 
    private void zg1_Load(object sender, EventArgs e) 
    { 

    } 
    } 
} 

Более обновление Я добавил zedgraphControl, добавив zedgraph.dll при объектно-реляционного проектирования в инструментарии VS2013.

Но все компоненты в моей панели инструментов выделены серым цветом в VS2013.

Когда я запустил код, у меня все еще была пустая форма.

Я попробовал проект на http://www.codeproject.com/Articles/5431/A-flexible-charting-library-for-NET

я могу получить карту, даже если все компоненты в моей панели инструментов являются также все неактивны в VS2013.

+1

ли вы назначить обработчик событий в свойствах формы? Недостаточно просто написать метод под названием «Form1_Load». – Blorgbeard

+0

Скопируйте кишки вашего Form1_Load, удалите весь метод, а затем дважды щелкните форму и добавьте событие еще раз, чтобы убедиться, что событие получило проводку. Затем скопируйте кишки. – thewisegod

+0

Я новичок, чтобы выиграть форму. Как добавить событие? и как убедиться в том, что событие получилось подключенным? – user3601704

ответ

0

Удалите следующие строки из Form1_Load и вы хорошо идти:

Console.WriteLine("Form1_Load is called"); 
ZedGraph.ZedGraphControl zg1 = new ZedGraphControl(); 
+0

Вы разместили точку останова на загрузке формы и подтвердили, что код запускается сейчас? – thewisegod

+0

Да, я поставил точку останова в private void Form1_Load() и подтвердил, что он был выполнен, но все равно пустой. – user3601704

+0

Когда вы на самом деле добавляете ZedGraphControl в свою форму? Вы перетащили его туда? – thewisegod