0

This is my first question here and, although it's probably a very nooby one, it's had me stumped for quite a while. I'm using a simplified example to explain.

On a Console Application, I have a public int 'x' set to 0 and a method 'test' which changes it to 1. When 'test' is called in Main, the value of X is now 1 (as expected).

    public int x = 0;

    public void test()
    {
        x = 1;
    }

    static void Main(string[] args)
    {
        Program program = new Program();
        program.test();
        Console.WriteLine(program.x);
        Console.ReadLine(); 
    }

However (and this is what I don't understand), when using a button_Click event to call the same 'test' method on a Windows Form Application, 'x' remains as 0:

    public Form1()
    {
        InitializeComponent();
    }

    public int x = 0;

    public void test()
    {
        x = 1;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form1 form = new Form1();
        form.test();
        MessageBox.Show("" + x);
    }
}

So to summarize, what I am wanting to happen is for 'test' to be called when the button is clicked, changeing the value of 'x' to 1. Can anyone explain why this isn't working?

Thanks!

Sammmm
  • 11
  • 1

2 Answers2

1

You've create two separate instances of Form1. Calling the test() method on the second instance is not going to affect the value of x in the first instance.

Change the button click event, so that you're not creating a new Form1.

private void button1_Click(object sender, EventArgs e)
{
    test();  // now it'll call test() on the current instance, and modify x as you expect

    MessageBox.Show("" + x);
}
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
0

Because is happening for the form that you created with Form1 form = new Form1();

Remove that line,call only test() and try again, it should work.