A
A
Anton Savchenko2015-07-16 13:08:46
Programming
Anton Savchenko, 2015-07-16 13:08:46

How to call a Form class method from another class?

There is one single form, and a non-static method is described in the class of this form. The fact is that to access this method from another class, you need an object of the Form class. So, where do you get it? Trying to create a new one throws a stack overflow exception. How to be?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
tex0, 2015-07-16
@Lapital

Manages the data on the form and contains the algorithmic part of the solution

then something like this
class Form1 : Form
{
    public Form()
    {
        // конструируем форму
        AnothertypeObject  = new AnotherType(this); // создаем объект контроллера в нужном нам месте. 
        //По умолчанию создаю в конструкторе формы
    }

    public AnotherType AnothertypeObject {get; private set;}
    // остальной код
}

public interface IFormController
{
    void DoSomething();
}

class AnotherType : IFormController
{
    private Form host_;
    public AnotherType(Form host)
    {
        host_ = host;
    }
   
    public void DoSomething()
    {
        // вызываем нужный метод объекта host_
    }
    // другая логика
}

the solution is clumsy, but for an example I think it will do.

P
pvlunegov, 2015-07-16
@pvlunegov

use Delegates. Read more about them, for example, here
or for example, everything is described here in a more human language.
In essence, you are using a delegate to create a reference to a method in any place and context.
Even on the form class method.
design an event, publish an event.
In the right place, you get a subscription to the event, you get the reaction to the event using a delegate.
Thus, your issue will be completely resolved.

R
Roman, 2015-07-16
@yarosroman

If the method does not use non-static members of the class, then it may be worth declaring it static, or in the constructor of another class, make a parameter that will pass a pointer to the form.

N
Necronel, 2015-07-17
@Necronel

What is the method responsible for and from what part should it be called?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question