Search code examples
c#winformsselectedvalueselectedindexchanged

SelectedIndexChanged called before class constructor in c#


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());
    }

Solution

  • 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.