Kris134
Kris134

Reputation: 55

Pass a variable from an open form C#

I have two forms, Form1 and Form2. Form1 has a variable int x. When the program is executed, Form1 is hidden and Form2 is shown; however i need to call the variable from the existing Form1.

I know the method to call the variable by calling a new instance of Form1.

     Form1 r = new Form1();
     r.x = 20;

But I want to know how to do it for an already opened Form1.

Take several cases, like if there are multiple variables that are called from Form1, by several forms (Form2, Form3, Form4 etc...). Any variable can be called from Form1 by the forms. Also, forms can call variables from other forms (Like if Form1 and Form2 is open, then Form3 can call variables from Form1 AND Form2)

I know its a huge list, but would really appreciate if anyone can find a good way to implement it.

Upvotes: 0

Views: 7405

Answers (7)

srsyogesh
srsyogesh

Reputation: 609

It doesn't matter whether which form is opened or closed. Your ultimate goal is to access a member from Form1 in Form2 isn't it? If that is the case when you create an instance of your Form2, do it like this

    Form1 objForm1 = new Form1();
    Form2 obj = new Form2(objForm1);

so that in form 2 class looks like this

    class Form2: Form
    {
         private Form1 form1Object;
         public Form2(Form1 obj)
         {
              form1Object = obj;
         }

         private void SomeMethodInForm2()
         {
              //Here you can access the variable in form1 like
              form1Object.PropertyNameYouWantToAccess;
         }
     }

The form 1 class can look like this

     class Form1: Form
    {
         public int PropertyNameYouWantToAccess{get;}

     }

Upvotes: 0

Bahadır EKİCİ
Bahadır EKİCİ

Reputation: 1059

Let's look at the situation.You have multiple forms in your application and you want to do access several variables these forms.

My guess is,

public static class GlobalVariables
{
    public static object MyVariable1 { get; set; }
    public static object MyVariable2 { get; set; }
}

So you can access variables everywhere in your project.

Upvotes: 0

NeverHopeless
NeverHopeless

Reputation: 11233

My guess is that you are looking for System.Windows.Forms.Application.OpenForms property which holds all the open forms in an array.

What you need to do is to check the type of each form and if it is equivalent to Form1 access the variable's value. Also, to access the variable outside the form you need to set its access modifier to either Public or make a corresponding property for it.

EDIT

Here is a sample code: (untested)

public partial class Form1 : Form
{

public int X;

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    X = 100;

    Form2 frm = new Form2();
    frm.Show();

    this.Hide();
}  
}



public partial class Form2 : Form
{

int local_X = 0;

public Form2()
{
    InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)
{
   foreach(Form f in System.Windows.Forms.Application.OpenForms)
   {
      if(typeof(f) == typeof(Form1))
    {
       local_X = f.X;   // access value here and set in local variable
    }
   }
}

private void button1_Click(object sender, EventArgs e)
{
   MessageBox.Show("Value of X is : " + local_X); // Show alert for value of variable on button click
}

}

EDIT

Or you can use constructor overloading to accomplish this task:

public partial class Form1 : Form
{

public int X;

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    X = 100;

    Form2 frm = new Form2(x); // pass variable to form2, if multiple values pass int array
    frm.Show();

    this.Hide();
}  
}



public partial class Form2 : Form
{

int local_X = 0;

public Form2()
{
    InitializeComponent();
}

// Overloading of constructor
public Form2(int X) // if multiple values pass int array
{
    InitializeComponent();
    local_X = x;  // capture value from constructor in class variable.
}

private void Form2_Load(object sender, EventArgs e)
{
   // no need to iterate here for now due to overloading value get passed during initialization.
}

private void button1_Click(object sender, EventArgs e)
{
   MessageBox.Show("Value of X is : " + local_X);  // display value if alert box.
}

}

Upvotes: 0

Hitesh
Hitesh

Reputation: 3860

You can do it in following ways,

in my case form1 is form4 and form2 is form5. please consider, :)

  1.  //code on form4:
    
    // this is by passing the reference of the form to other form
    public partial class Form4 : Form
    
    {
    
    public int a { get; set; }
    public int b { get; set; }
    
    public Form4()
    {
        InitializeComponent();
    }
    
    private void Form4_Load(object sender, EventArgs e)
    {
    
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        a = 5;
        b = 6;
    
        Form5 frm5 = new Form5();
    
        frm5.frm4 = this;
    
        this.Close();
    
        frm5.Show();
    }
     }
    
    // code on form5
    
    public Form4 frm4 { get; set; }
    
    private void Form5_Load(object sender, EventArgs e)
    {
        int x = frm4.a;
        int y = frm4.b;
    }
    
  2. Also you can have a class file in which the instance of the form1 will be static, so that you can use that instance on form2 to refer to the form1's properties.

Let me know, if it does not solve your problem.

I hope it will help you. :)

Upvotes: 1

Yatrix
Yatrix

Reputation: 13775

Create a public property on the form itself. Have the get accessor return the form value. You can call it like this. Form1.MyProperty;

public string MyPrperty {
  get {
      return Form1.txtExample.text;
  }
}

EDIT:

You can return a dictionary of all of those values if you have that many to return at a time. I would seriously consider rethinking your form if you have 20-40 values being filled. That sounds like a poor user experience to me.

Upvotes: 1

user2499652
user2499652

Reputation:

i think there is a reason that you wouldn't try System.Properties.Settings.Default accessible from Project Menu --> Properties in visual studio...

Thanks...

Upvotes: 0

Adriaan Stander
Adriaan Stander

Reputation: 166356

You will have to have a reference to the "already opened" form1 instance, so that you can reference the value of x on that form.

So, lets say that Form2 instantiates the hidden form1. You will have to have a reference in form2 to the form1, to reference the variable.

OK, Lets say this is the code for form2

public partial class Form2 : Form
{
    private Form1 f;
    public Form2()
    {
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {
        f = new Form1
                {
                    Visible = false
                };
        int x = f.X;
    }
}

and then code for form1

public partial class Form1 : Form
{
    public int X { get; set; }

    public Form1()
    {
        InitializeComponent();
        X = 20;
    }
}

and you need to ensure that the form luanched from the program class is

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form2());
    }
}

Upvotes: 2

Related Questions