Question

In my project on the WindowsForms, if I have a static instance inside the form, when I'm opening my form at the first time, it works. But if I'll close it and open again, the form will be empty. Why can it be?

public partial class Computer : Form
    {
        static Indicators indicators = new Code.Indicators();
    }

P.S. I'm making it static, because I want to save it's value after the form will be closed.

Edit 1: Opening the form

private void button3_Click(object sender, EventArgs e)
        {
            Computer computer = new Computer();
            computer.ShowDialog();
        }

Edit 2: Computer Form

namespace WF
{
    public partial class Computer : Form
    {
        static Code.Indicators indicators = new Code.Indicators();

        public Computer()
        {
            if (indicators.isComputerAlreadyRunning == false)
            {
                InitializeComponent();
                pictureBox1.Image = Properties.Resources.Computer1;
                indicators.isComputerAlreadyRunning = true;
            }
        }

        // My not successful try to save the value of the variable
        public Code.Indicators ShowForm()
        {
            return new Code.Indicators(indicators.isComputerAlreadyRunning);
        }
    }
}
Was it helpful?

Solution 2

According to the constructor in the Computer class, the indicators.isComputerAlreadyRunning is set to true the first time the form is created.

So when Computer is created the second time, the if condition will fail and the whole if block will be skipped. That means your InitializeComponent(); won't get run and hence nothing in the form will shows up.

Put the InitializeComponent(); outside the if clause to make it work.

OTHER TIPS

I don't think that static members work well with the Windows Form lifecycle.

I suggest you make Indicators a normal instance member of your form. To preserve state beyond the life of a form you can copy your state from the form and copy it back to the form when you open it.

// Keep this in the proper place 
var indicators = new Code.Indicators();

...

// Copy back and forth for the life time of the form
using (var form = new Computer())
{
    form.Indicators.AddRange(indicators);
    form.Close += (s, e) => 
        {
            indicators.Clear();
            indicators.AddRange(form.Indicators);
        }
}

...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top