-2

Where should i declare the variables i like to use in windows forms?

    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

     int iMyvariable = 1;

   }

    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

     iMyvariable++;
   }

Running the code gives the following error:

error C2065: 'iMyvariable' : undeclared identifier

imi007
  • 23
  • 2
  • 5
  • 3
    This is nothing to do with winforms or visual studio - this is pretty much fundamental c++ - if you don't understand about function level variable scope, you need to go back to your textbooks! – benjymous Nov 12 '13 at 14:18
  • you should define it outside your functions as a global variable – benka Nov 12 '13 at 14:19

1 Answers1

2

In your current code iMyvariable is saved as a local variable as opposed to a global variable. Outside of the brackets around the event handler it ceases to exist.

Instead try declaring the variable globaly- near the top of the class, then assign it inside your method. (Note: you must be inside of a method to make a variable assingnment.)

Your code should look something like this:

public class something{

  int myVariable;
 private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {

  iMyvariable = 1;

 }

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {

 iMyvariable++;
  }
 }