[英]How to build a chart at runtime
In a winforms project, if I add a chart control at design time, the following code builds and displays a chart perfectly.在winforms项目中,如果我在设计时添加图表控件,下面的代码就可以完美的构建和显示图表。
However, without a chart1
on my form (at design time), if I create the same chart1
at run-time:但是,如果我的表单上没有chart1
(在设计时),如果我在运行时创建相同的chart1
:
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.