In a winforms project, if I add a chart control at design time, the following code builds and displays a chart perfectly.
However, without a chart1
on my form (at design time), if I create the same chart1
at run-time:
Chart chart1 = new Chart();
add the series,
and then add it to my form:
this.Controls.Add(chart1);
an empty chart displays as if the series was not added.
I need to build my chart completely at run-time. Can anyone help me please?
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace Test
{
public partial class Charts : Form
{
public Charts()
{
InitializeComponent();
//Chart chart1 = new Chart();
chart1.Series.Clear();
chart1.Titles.Add("My Chart");
chart1.Series.Add("Load");
chart1.Series["Load"].ChartType = SeriesChartType.Column;
chart1.Series["Load"].Points.AddXY(1, 40);
chart1.Series["Load"].Points.AddXY(2, 60);
chart1.Series["Load"].Points.AddXY(3, 80);
chart1.Series["Load"].Points.AddXY(4, 100);
chart1.Series["Load"].Points.AddXY(5, 110);
chart1.Series["Load"].Points.AddXY(6, 80);
chart1.Series["Load"].Points.AddXY(7, 70);
//this.Controls.Add(chart1);
}
}
}
I just don't think you have managed to get all of the code out of the designer properly. Here's a minimal example that works for me:
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var chart = new Chart();
chart.ChartAreas.Add(new ChartArea());
var series = new Series();
series.Points.AddXY(1.0, 42.0);
series.Points.AddXY(2.0, 47.0);
series.Points.AddXY(3.0, 53.0);
chart.Series.Add(series);
chart.Location = new System.Drawing.Point(10, 10);
chart.Size = new System.Drawing.Size(500, 400);
this.Controls.Add(chart);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.