简体   繁体   中英

Access form methods and variables from a class and vice versa in C#

I am trying to finds a way to have access to methods and variables of a form and a class from each other using instance. Here is my code:

My form code is:

public partial class Form1 : Form
{
    int var1 = 0;

    public Form1()
    {
        InitializeComponent();
        Glob glob = new Glob(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {

    }
}

and my class code is:

public class Glob
{
    private Form1 _form;

    public Glob(Form1 parent)
    {
        _form = parent;
    }

    public int Func1()
    {
        return 10;
        _form.var1 = 10;
    }
}

I can call form methods from my class, but I can not call class methods from button1_Click event! What is wrong with my code please?

This will never set the property:

public int Func1()
{
    return 10;
    _form.var1 = 10;
}

The function returns before the property is set. You should be getting an unreachable code warning.

Also, your var1 variable is private. You need to make it public (capitalize it too). This is so it can be accessed outside of where its declared:

public int Var1 { get; set; }

In addition.. you want your Glob instance to be form level:

private Glob _glob;

public Form1()
{
    InitializeComponent();
    _glob = new Glob(this);
}

Then you can call it in the click event:

private void button1_Click(object sender, EventArgs e)
{
    _glob.Func1();
}

That's because your scope for glob is local to your constructor. Declare it as a module level variable and it will work just fine.

public partial class Form1 : Form
{
    int var1 = 0;
    Glob glob;

    public Form1()
    {
        InitializeComponent();
        glob = new Glob(this);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        glob.Func1();
    }
}

[Edit]

Simon Whitehead's answer gives more detail of the other problems you have, but mine addresses your specific question of "Why can't I call glob from my button click?"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM