質問

I create a class in my c# application called Acquisti. Then I initialize it in form constructor and then I call a method of this class in combobox SelectedIndexChanged event. The problem is that when I run the program I get an error that says that the object of the Acquisti class that I created is null. This means that SelectedIndexChanged event is called before than form constructor, isn't it? I also tried with SelectedValueChanged event but I have the same problem. Here is the simple code:

Acquisti _acquisti;

    public Form1()
    {
        InitializeComponent();
        WindowState = FormWindowState.Maximized;

        for (int i = DateTime.Now.Year; i >= 2000; i--)
            annoAcquisti.Items.Add(i);

        annoAcquisti.SelectedIndex = 0;

        _acquisti = new Acquisti();
    }



    private void annoAcquisti_SelectedIndexChanged(object sender, EventArgs e)
    {
        _acquisti.load(ref acquistiDGV, annoAcquisti.SelectedItem.ToString());
    }
役に立ちましたか?

解決

SelecteIndexChanged is called due to line:

annoAcquisti.SelectedIndex = 0;

and you are initializing _acquisti after that. You can move the line before like:

public Form1()
{
    InitializeComponent();
    _acquisti = new Acquisti(); //move it here
    WindowState = FormWindowState.Maximized;

    for (int i = DateTime.Now.Year; i >= 2000; i--)
        annoAcquisti.Items.Add(i);

    annoAcquisti.SelectedIndex = 0;

}

Since the control moves to SelectedIndexChanged event and at that point _acquisti is still null, that is why you get the exception.

他のヒント

This means that SelectedIndexChanged event is called before than form constructor, isn't it?

No. It is called before the form constructor is FINISHED - as a result of actins in the constructor.

That is simple to fix - instead of playing around with the controls first initialize them and then play around.

Move the _Ackquisti = new.... line before the loop. Finishied.

In fact, initialization should happen first - before any further manipulation. InitializeCOmponent(), then other initialization, then more complicated stuff.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top