appski
appski

Reputation: 159

Passing a form as a reference into a class, but where should I call it from?

I'd like to pass my form as a reference into a class, so the class object can access public methods from the form. I've tried it in a few different places, but each one has a few limitations.

Is there a way to instantiate the class from outside of the events, but still pass in the form?

namespace MyApplication
{
    public partial class Form1 : Form
    {
        //If I instantiate the class here, the form seemingly doesn't exist yet 
        //and can't be passed in using "this."
        Downloader downloader = new Downloader(this);

        private void Form1_Load(object sender, EventArgs e)
        {
            //If I instantiate the class here, the form can be passed in, but the
            //class object can't be seen outside of this event.
            Downloader downloader = new Downloader(this);
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
            //If I instantiate the class here, the form can be passed in, but the
            //class object can't be seen outside of this event.
            Downloader downloader = new Downloader(this);

            downloader.dostuff();
        }
    }
}

Upvotes: 0

Views: 2261

Answers (2)

Brian Warshaw
Brian Warshaw

Reputation: 22984

namespace MyApplication
{
    public partial class Form1 : Form
    {
        Downloader downloader;
        // either of the following two will work
        private void Form1_Load(object sender, EventArgs e)
        {
            downloader = new Downloader(this);
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
            downloader = new Downloader(this);
        }
    }
}

Upvotes: 1

Andre Calil
Andre Calil

Reputation: 7692

You are almost there. Change it to:

namespace MyApplication
{
    public partial class Form1 : Form
    {
        private Downloader downloader;

        private void Form1_Load(object sender, EventArgs e)
        {
            this.downloader = new Downloader(this);
        }

        private void downloadButton_Click(object sender, EventArgs e)
        {
           downloader.Whatever();
        }
    }
}

Upvotes: 5

Related Questions