創建圖表:的NullReferenceException加入點時以圖表
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()被調用在負載情況下的第一件事的主要形式。
的代碼行導致該錯誤是內部的
this.BeginInvoke(new MethodInvoker(delegate()
在的SerialPort的DataRecieved事件後「mainChart」的
本地值出現誤差i.imgur.com/LZSY3Iw .png
所有這些代碼工作正常,直到我關閉「Child_Chart」。
我在主帖中增加了更多信息。 – user2705775