创建图表:
private Chart mainChart;
private void createChart()
{
mainChart = new Chart
{
Dock = DockStyle.Fill,
Name = "chart1",
};
mainChart.ChartAreas.Add(new ChartArea());
mainChart.Legends.Add(new Legend());
mainChart.ChartAreas[0].AxisX.Minimum = 1;
for (int i = 0; i < 32; i++)
{
mainChart.Series.Add(new Series
{
Name = "test" + i,
LegendText = "Test " + (i + 1).ToString().PadLeft(2, '0'),
ChartType = SeriesChartType.FastLine,
});
}
}
图表属性:
public Chart chart
{
get
{
return mainChart;
}
set
{
mainChart = value;
Form activeChild = FormAlreadyLoaded("Child_Chart");
if (activeChild != null)
{
Chart frmchart = activeChild.Controls.Find("chart1", true).FirstOrDefault() as Chart;
frmchart = mainChart;
}
}
}
FormAlreadyLoaded方法:
private Form FormAlreadyLoaded(string formName)
{
foreach (Form frm in this.MdiChildren)
if (frm.Name.Equals(formName))
return frm;
return null;
}
Child_Chart是一个简单的表单,在“加载”方法中使用它:
MainForm parent = this.MdiParent as MainForm;
this.Controls.Add(parent.chart);
添加到图表(发生错误的地方)
chart.Series[i].Points.AddXY(value1,value2);
例外文字:
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.DataVisualization.Charting.Chart.get_Series()
at Oasis.MainForm.<>c__DisplayClass13.<ProcessSerial>b__11() in MainForm.cs:line 355
at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
at System.Windows.Forms.Control.InvokeMarshaledCallbacks()
更多信息:
createChart()是主窗体的load事件中调用的第一个东西。
导致错误的代码行位于
中this.BeginInvoke(new MethodInvoker(delegate()
在serialPort的DataRecieved事件中
出现错误后'mainChart'的本地值i.imgur.com/LZSY3Iw.png
所有这些代码都可以正常工作,直到我关闭“Child_Chart”。
答案 0 :(得分:0)
由于series [i]的Points属性可能是非基本类型,您需要使用'new'关键字
使用其构造函数初始化它答案 1 :(得分:0)
你确定chart
不是什么?我没有看到调用CreateChart()
的位置,我没有看到私有字段mainChart
被实例化的其他任何地方。
除此之外,您需要打破错误并查看哪个是空引用。它可以是chart
,chart.Series
或chart.Series[i]
,依此类推整个声明。