How can I create several global variables in Winforms C #?

0

I mean, for example, that you have a variable called "A" in a form 1 and that you can change the value of "A" from form 2 or 3 (all)

    
asked by Sebastián García 12.03.2018 в 18:37
source

2 answers

-1

If I remember correctly, you can access that variable including the name of the source form in the call to the variable. Something like:

In form 2:

Form1.A = "nuevo valor";
    
answered by 12.03.2018 / 18:44
source
1

As mentioned by @gbianchi, there is no global module, and unless your form is static directly you could not access that variable, but you can choose a similar option using Encapsulation (Refactorization)

Example:

//Formulario 1...
 private string tuVariable = string.Empty;

 public string TuVariable
 {
      get { return tuVariable; }
      set { tuVariable = value; }
 }
  

But in order to access this variable you must instantiate the formulario1 from where you want to access the variable like this:

public partial class Formulario2 : Form
{
    public Formulario2()
    {
        InitializeComponent();
    }

   //......
   //......

   formulario1 frm = new formulario1();
   frm.TuVariable; //Aqui puedes asignarle valor o obtener su valor actual.
}
  

But the correct thing would be to create a static class to access the variables from all the forms, something like this:

public static class TuClaseEstaticaCompartida
{
    public static string TuVariable;
    public static int OtraVariable;
    // otras variables estáticas
}

And from the other forms you call them like any other common variable:

public void Formulario1()
{
    TuClaseEstaticaCompartida.TuVariable= textBox1.Text;
}

public void Formulario2()
{
    MessageBox.Show(TuClaseEstaticaCompartida.OtraVariable.ToString());
}

Note: Static classes can only have static members.

    
answered by 12.03.2018 в 20:58