I am using Visual Studio 2010 Express Edition, and I am developing a basic game application. It involves a New Game button that is clearly named "NewGame" in 'Form1.cs'. But when I use this code:

NewGame.Click += new EventHandler(newGame);

in 'Program.cs' I get the error message "Error 1 - The name 'NewGame' does not exist in the current context". Any help is appreciated, thanks in advance.

I'm guessing you set the wrong property. Did you set the Name property or the Text property?

check the name properly and also check the access specifiers i.e. check where you have created the button is that a global one (created in the form) or you created it in any function

your button must be globle....

using System;
using....

namespace yourproject
{
	
	public class Program : System.Windows.Forms.Form
	{
		private System.Windows.Forms.Button NewGame;
                
                public Program()
		{
			InitializeComponent();
                         NewGame.Click += new EvenHandler(NewGame_Click);           
                 }
            }
      }

and your event declaration is not correct...it should be NewGame_Click

Hope this helps

To add:

namespace yourproject
{	
	public class Program : Form
	{
		private Button NewGame;                
                public Program()
		{
			InitializeComponent();
                        1st you need to create a button:
                        NewGame = new Button;
                        NewGame.Location = new Point (100,100);
                        NewGame.Text = "press me";
                        NewGame.Name = "button1";
                        NewGame.Size = new Size(40, 23);                        
                        NewGame.Click += new EvenHandler(NewGame_Click);           
                        this.Controls.Add(NewGame);
                 }

                 private void NewGame_Click(object sender, EventArgs e)
                 {
                       //do the code on the button click here
                 }
            }
      }
}

Problem fixed, I appreciate the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.