keebler
keebler

Reputation: 45

Object initialized in form constructor is null

I have a problem with object ChartSettings from my form initialization.

It's my own class added below Form1 code:

public partial class Form1 : Form
{


    public Form1(bool archivePlotPreview)
    {
        InitializeComponent();
        ChartSettings chartOne = new ChartSettings(this.chart1, archivePlotPreview);
    }

    public ChartSettings chartOne;

    //Form1 variables and functions
}

public class ChartSettings
{

    public ChartSettings(Chart settingsRelatedChart, bool archivePlotPreview)
    {
        // przypisanie wykresu do ktorego odnosza sie ustawienia
        ChartObject = settingsRelatedChart;
        ChartObject.MouseMove += new System.Windows.Forms.MouseEventHandler(this.chart1_MouseMove);

        barchivePlotPreview = archivePlotPreview;

    }

    // other variables and functions
}

The reason of creating this class is the need of additional variables related to Chart object (chart1 added in Designer window) like CSV save options, min/max markers options etc. So in constructor of Form1 I've added line creating my ChartSettings object as can be seen above. It assings chart1 to it and in further code I'd like to use chartOne.ChartObject instead of this.chart1.

When I create new Form1 instance a window shows up, chart1 is visible etc. but when I push the "Load data" button where I use chartOne.ChartObject reference it crashes because chartOne is null :/ Direct operations on this.chart1 seems to be ok. When I debug my code, chartOne IS created in constructor and is not a null, but when I press mentioned button it acts like above anyway. Why my chartOne dissapears somewhere between? And how should it be done right way?

Upvotes: 1

Views: 2971

Answers (2)

daryal
daryal

Reputation: 14919

you are not initializing the property ChartSettings chartOne but you are creating an instance inside constructor, and it is disposed when constructor finishes. It means you have never initialized the class level property chartOne; thus it will be always null.

When you use this.chartOne you are declaring that you want to use the property defined in the class.

Change it to;

public ChartSettings chartOne{ get; set;}

public Form1(bool archivePlotPreview)
{
    InitializeComponent();
    chartOne = new ChartSettings(this.chart1, archivePlotPreview);
}

Upvotes: 7

whastupduck
whastupduck

Reputation: 1166

The ChartSettings chartOne you created in the constructor is a different object from the global one you declared in your class. The ChartSettings chartOne in the constructor is only available in that scope thus the ChartSettings chartOne of the class remains null.

Upvotes: 3

Related Questions