Kerberos
Kerberos

Reputation: 1256

Call a public method of main class from another class

My main Form1.cs as below

   public partial class Form1: Form
    {
        Test _Test = new Test()

        public Form1()
        {
            InitializeComponent();
            _Test._TestMethod();
        }

        public void _MainPublicMethod(string _Message, string _Text)
        {
            MessageBox.Show(_Message);
            TextBox1.Text = Text;
        }
    }

My Test.cs as below

class Test
{
    Form1 _Form1 = new Form1();

    public void _TestMethod()
    {
        _Form1._MainPublicMethod("Test Message", "Test Text");
    }
}

When i debug my project, codes doesn't work.

Thank you in advance.

Upvotes: 2

Views: 15593

Answers (3)

Steve
Steve

Reputation: 216313

Your code shows a common misunderstanding (or a lack of understanding of a basic OOP principle).
When, inside form1, your code calls _Test._TestMethod() you are calling a method that 'belongs' to the instance of class Test defined and initialized in your form1. In turn, that instance try to call the method _MainPublicMethod defined in the class Form1. But, because to call that method (an instance method, not a static method) you need an instance of Form1, you declare and initialize ANOTHER instance of Form1

You end up with two instances of the class Form1 opened and the call is resolved by the second instance of Form1 not from the instance that had called _TestMethod initially.

To avoid this problem you need to pass the reference to the instance of Form1 that calls Test_Method and use that instance inside Test to call back on the public method.

So, when calling Test_Method pass the current instance of Form1

   public Form1()
   {
        InitializeComponent();
        _Test._TestMethod(this);
   }

and in Test.cs

class Test
{
    Form1 _frm = null;

    public void _TestMethod(Form1 f)
    {
        _frm = f;
        _frm._MainPublicMethod("Test Message", "Test Text");
    }
}

Upvotes: 1

Roger Johansson
Roger Johansson

Reputation: 23214

I guess you want to call the mainpublicmethod on the owner form, not a new instance of the owner form. like this:

public partial class Form1: Form
{
    Test _Test = new Test()

    public GrabGames()
    {
        InitializeComponent();
        _Test._TestMethod(this); //pass this form to the other form
    }

    public void _MainPublicMethod(string _Message, string _Text)
    {
        MessageBox.Show(Message);
        TextBox1.Text = Text;
    }
}

class Test
{
   public void _TestMethod(Form1 owner)
   {
       //call the main public method on the calling/owner form
       owner._MainPublicMethod("Test Message", "Test Text");
   }
}

Upvotes: 2

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

You can modify this code, add parenthesis ()

Form1 _Form1 = new Form1();

Upvotes: 2

Related Questions