Search code examples
c++winformsvisual-studio-2010variablesdeclare

Declare variables in Microsoft Visual C++?


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


Solution

  • 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++;
      }
     }