Connection Program.cs and Form.cs

I have a function in my Form.cs that I want to call in my program program.cs

But if the function is not static, program.cs cannot use it. And if it is static, Form.cs cannot use it because it includes controls that are not static.

I can remove my program.cs code and find a way to do the same in my form.cs, but I was wondering if there is an easier way.

Typically, a function in the form of .cs does

public void Toggle()
    {
        MyDomainUpDown.SelectedIndex = 3;
    }

Program program.cs:

MainForm.Toggle();
+3
source share
3 answers

Why can't you access it from your program.cs?

You can easily define a variable to save the form and then reference it:

static class Program
{
    // Any method can now access the form
    static Form1 MyForm;

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        MyForm = new Form1();
        Application.Run(MyForm);
    }

}
+3

Form program.cs, / .

Program.cs :

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
}

new MainForm() . , :

        var mainForm = new MainForm();
        mainForm.MethodToCall();
        Application.Run(mainForm);
0

I'm not sure what your situation is, but if you don't have a reference to myForm, why or when you want to call some non-static method defined in MyForm?

If, on the other hand, you have a link to it, just make it MyFunctionpublic and call it normally:

 class Program
 {
     MyForm myForm = new MyForm();
     ....
     myForm.MyFunction(); //call here
 }

 public partial class MyForm: Form
 {
     ....
     public int MyFunction() {...}
 }

You can also make it static and add a reference to the MyForm instance in the function arguments if there was any practical reason for this.

 public partial class MyForm: Form
 {
     ....
     public static int MyFunction(MyForm myForm) {...}
 }
0
source

All Articles