Does anybody have some experience working with charts in .NET
? Specially I want to create them programmatically.
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 System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0,10);
int second = rnd.Next(0,10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
mych.Show();
Controls.Add(mych);
mych.Show();
}
}
}
I'm trying to use .NET (.net 4, Visual Studio 2010)
chart, but the random generated data set, doesn't appear. The chart remained blank. I searched for examples and only found ones like this , and, yes with manual "drag" method it works. I have no idea why the data I programmatically generate doesn't appear.
Try to include these lines on your code, after mych.Visible = true;
:
ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);
You need to attach the Form1_Load
handler to the Load
event:
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 System.Windows.Forms.DataVisualization.Charting;
using System.Diagnostics;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
Random rnd = new Random();
Chart mych = new Chart();
mych.Height = 100;
mych.Width = 100;
mych.BackColor = SystemColors.Highlight;
mych.Series.Add("duck");
mych.Series["duck"].SetDefault(true);
mych.Series["duck"].Enabled = true;
mych.Visible = true;
for (int q = 0; q < 10; q++)
{
int first = rnd.Next(0, 10);
int second = rnd.Next(0, 10);
mych.Series["duck"].Points.AddXY(first, second);
Debug.WriteLine(first + " " + second);
}
Controls.Add(mych);
}
}
}
Add a reference to System.Windows.Form.DataVisualization
, then add the appropriate using statement:
using System.Windows.Forms.DataVisualization.Charting;
private void CreateChart()
{
var series = new Series("Finance");
// Frist parameter is X-Axis and Second is Collection of Y- Axis
series.Points.DataBindXY(new[] { 2001, 2002, 2003, 2004 }, new[] { 100, 200, 90, 150 });
chart1.Series.Add(series);
}
Source: Stackoverflow.com