Updating GUI form Separate Class

Go To StackoverFlow.com

2

so I've been searching for the past few hours, reading on everything about how to update the GUI of the form from another class. I tried, backgroundworker, and Invoke, but nothing seems to work, or rather I'm not doing it right. (I'm still pretty new to c#) So..why doesn't this method work at all?

Form 1:

 private void button2_Click_1(object sender, EventArgs e)
    {
        prog.stuff();
    }
    public void Updateprogressbar(int input)
    {
        progressBar1.Value = input;

    }

Class Prog

 public static void stuff()
    {
        Form1 f = new Form1();
        int up = 100;
        f.Updateprogressbar(up);
    }

I know this is probably a very easy question, but I still can't figure it out. The progress-bar just won't update. And I do have it all enabled to public in the properties. Thanks anyway.

2012-04-04 02:51
by Movieboy


2

private void button2_Click_1(object sender, EventArgs e)
    {
        prog.stuff(this);
    }
    public void Updateprogressbar(int input)
    {
        progressBar1.Value = input;

    }


 public static void stuff(Form f)
    {
        int up = 100;
        f.Updateprogressbar(up);
    }

So you can see the reason your code doesn't work is because your instantiating a new instance of Form1 thats only alive in the stuff() method. In my code I pass a reference of Form1 into class Prog.Stuff there by giving me access to form1's methods.

2012-04-04 02:57
by Jeremy Thompson
Omg! Thanks! Did the trick! Good explanation too...I think I need to read my c# for dummies a little more now - Movieboy 2012-04-04 03:08
+1 welcome to StackOverflow, we love it when questions are well written and have sample code of what you've tried that doesn't work. Do read up on that book. Coding is a fusion of Art, Science, Math and Technology (like movie making) and without a good book as a reference it can be hard googling to get your head around some things - Jeremy Thompson 2012-04-04 03:26
Ads