I am getting a odd error that I cant recall ever getting before. I am trying to make a few menus for a small game but somehow something is wrong with my reference to Form1.

Here is the code:

public partial class Form1 : Form
    {
        Form2 Form2 = new Form2();
        Form3 Form3 = new Form3();
        public string difficulty = "Makkelijk";
        public string guesses = "Normaal";

        public Form1()
        {
            InitializeComponent();
        }

        private void playButton_Click(object sender, EventArgs e)
        {
            //Form3.difficulty = difficulty;
            //Form3.guesses = guesses;
            Form3.Show();
            this.Hide();
        }

        private void optionsButton_Click(object sender, EventArgs e)
        {
            Form2.Show();
            this.Hide();
        }

        private void exitButton_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }

Form2:

public partial class Form2 : Form
{
    Form1 Form1 = new Form1();

    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        //Woord toevoeg query
    }

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void button3_Click(object sender, EventArgs e)
    {
        //Form1.difficulty = comboBox1.Text;
        //Form1.guesses = comboBox2.Text;
        this.Close();
    }
}

Is there anything wrong with this?

Thanks in advance.

有帮助吗?

解决方案 3

As said before, circular initialization is causing your exception.

One way of solving it is to make Form2 accept Form1 as constructor parameter.

Form1 form;

public Form2(Form1 form1)
{
    form = form1;
    InitializeComponent();
}

其他提示

This is because you are initializing the Form2 inside the Form1 and in Form2 you are initializing Form1, which makes circular initialization and causes to stackoverflow exception.

You are creating a new Form1 in the ctor of Form2 and Form2 in the ctor of Form1.
Each time you create one of those, you create the other as well and so you get into an infinite loop which evantualy fills up your stack.

The first line of Form1 creates a new Form2. The First line of Form2 creates a new Form1. This will keep happening until you run out of memory.

Remove the

Form1 Form1 = new Form1();

from the Form2 definition.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top