Create chart:
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,
});
}
}
Chart property:
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 method:
private Form FormAlreadyLoaded(string formName)
{
foreach (Form frm in this.MdiChildren)
if (frm.Name.Equals(formName))
return frm;
return null;
}
Child_Chart is a simple form with this in the "Load" method:
MainForm parent = this.MdiParent as MainForm;
this.Controls.Add(parent.chart);
Add to chart (where the error happens)
chart.Series[i].Points.AddXY(value1,value2);
Exception text:
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()
More information:
createChart() is the first thing called in the load event of the main form.
The line of code that causes the error is inside a
this.BeginInvoke(new MethodInvoker(delegate()
in the DataRecieved event of a serialPort
Local values of 'mainChart' after the error appears i.imgur.com/LZSY3Iw.png
All this code works fine, until I close "Child_Chart".