NESHOM
NESHOM

Reputation: 929

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?

Upvotes: 0

Views: 104

Answers (2)

Jane S
Jane S

Reputation: 1487

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?"

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65049

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();
}

Upvotes: 2

Related Questions