Using a method from one .cs file class in another .cs files class

Viewed 81829

I have 2 .cs files each with a class in it. How do I call a method in a class from Form1.cs in another class inside of Form2.cs?

Looks something like this...

Form1.cs

public partial class Class1 : ClassContainer
{
    public void awesomeMethod()
        {
        }
}

Form2.cs

class Class2 : SomethingChanged
{
    public void decentMethod()
    {
    }
}

I would like to call awesomeMethod() inside of the decentMethod(). Thanks.

6 Answers

Assume the main Form is frmMain. Make a static declaration outside frmMain()'s constructor; assign it inside that same constructor:

public static frmMain p_frmMain = null;
public frmMain()
{
    InitializeComponent();
    :
    p_frmMain = this;
}

From another class (using main's namespace in that same solution), call, say, main's 'btnHelloWorld_Click()' method:

AnotherClass_EventHandler(object sender, EventArgs e)
{
:  // Call frmmain()'s 'btnHelloWorld_Click' event:
   frmMain.p_frmMain.btnHelloWorld_Click (sender, e);
:
}
// Quick, dirty and done.
Related