Object reference is required for the non static field

92 views Asked by At
namespace Pong
{
    public partial class Menu : Form
    {
        public Menu()
        {
            InitializeComponent();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {

        }

        private void PlayButton_Click(object sender, EventArgs e)
        {
            PongForm form = new PongForm();
            PongForm.Show();
            this.Close();
        }

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

Can someone explain why I'm getting an error? I've had a look online and think it should work. I'm trying to change to a new form on button click.

3

There are 3 answers

0
Trey On

Change "PongForm.Show();" to "form.Show(). To eloborate: you are attempting to call the class, not the instance you created.

1
Zoran Horvat On

In this function you should refer form, not PongForm:

private void PlayButton_Click(object sender, EventArgs e)
{
    PongForm form = new PongForm();
    form.Show();
    this.Close();
}
0
Dustin On

to just add to what others have said. you probably don't want multiple of the same forms open. I cant comment or I would have done that instead. hope this solves your problem.

if (Application.OpenForms["PongForm"] != null) { Application.OpenForms["PongForm"].WindowState = FormWindowState.Normal; Application.OpenForms["PongForm"].BringToFront(); } else { PongForm form = new PongForm(); form.Show(); }