nik
nik

Reputation: 25

Change variable in main form (Winform c#)

I'm new to Visual studio and I created a Project with a Form1 and another Form called Form2. Form2 will be opened by this code:

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

When i click a Button in Form2 I want to change a variable in my Form1. Is there an easy way to do this?

Upvotes: 1

Views: 1797

Answers (3)

Ahmed Anwar
Ahmed Anwar

Reputation: 678

You can create a static variable in Form1, the variable that you need to change. Let it be int x for example

public static int x= 0;

The line up there must be defined in Form1 Then inside the function in Form2 for the button click:

Form1.x = //value;

Upvotes: 1

AustinWBryan
AustinWBryan

Reputation: 3326

In Form2 ctor:

public Form2(Form1 fm)
{
    this.Fm = fm;
}

And call it in Form1, like this:

Form2 form = new Form2(this);
form.Show();

This is useful if Form1 is not a single instance.

Upvotes: 1

Ramazan Binarbasi
Ramazan Binarbasi

Reputation: 787

Assuming Form1 is single instance, you can declare a variable as public static in Form1 code

public static int MyVariable;

then you can access it within Form2 like below:

Form1.MyVariable = 5;

Upvotes: 1

Related Questions