-3

I have a Form1.h and a Form2.h

Form1.h is already including Form2.h because i start Form2 by clicking a button in Form1. So how would i pass a variable from Form1.h to Form2.h

Here is an example of Form1.h

#include "Form2.h"

String^ str = "Hello World"; //This variable needs to be passed to Form2.h

//Other windows forms application code here

An example of Form2.h

//#include "Form1.h" this will cause an error

//How would i pass variable str to here?

//Other windows forms application code here

Edit:

This is how i fixed it

This is how i fixed it.

Form1.h

#include "Form1.h"

Form2^ frm = gcnew Form2;
frm->Username = "text here";//This passes the variables.
frm->Password = "other text";

Form2.h

public: String^ Username;
public: String^ Password;
FreelanceCoder
  • 596
  • 2
  • 8
  • 12

3 Answers3

1

Not exactly sure what your asking, but im assuming that you want to set a variable in Form2 class from inside Form1 class? If so:

class Form1{
  private:
    int data;
  public:
    Form1(){data=4;}
    int getData(){return data;}  //returns Form1 data variable
    void setForm2Data(Form2&);   //sets Form2 data
};

class Form2{
  private:
    int data;
  public:
    void setData(int inData){data = inData;}
};

void Form1::setForm2Data(Form2 &o){
  o->setData(getData());  //argument is a Form2 object, "setData" can set that objects data variable
}
mn.
  • 796
  • 6
  • 12
0

You get an error because your preprocessor directives cause double inclusion. To avoid this you can use pragma guards

Form1.h:

#ifndef FORM1_H
   #define FORM1_H
   #include "Form2.h"
   extern string str = "Hello World";
#endif

Form2.h:

#include "Form1.h"
Skeptiker
  • 21
  • 3
0

There are several ways.. one is to use global variables (not necessarily the best way.. depends per case basis)

First, you can solve the multiple inclusion problem by using include guard.

Then you can declare a global variable using extern keyword in the header, and plug in the value in the implementation file.

For example:

//file: mylib.h
#ifndef MYLIB_H
#define MYLIB_H
extern int myGlobalVar;
#endif

//file: mylib.cpp
#include "mylib.h"
int myGlobalVar = 123;

Now you can #include "mylib.h" anywhere in other file as many time as you like and access the same variable

gerrytan
  • 40,313
  • 9
  • 84
  • 99