Home > Mobile >  Calling method from another class - Winforms C#
Calling method from another class - Winforms C#

Time:01-24

I am trying something like below and I am getting red lines under any formDesign commands such as messageBox, dataGridView etc.

I want to put the body of the methods in a seperate .cs page for neatness and call them from mainForm.cs

Is this the wrong way to call methods

mainForm.cs

namespace App{
      public partial class mainForm : Form{
             private void saveCSVbutton_Click(object sender, EventArgs e){
                className.method();
             }
      }
}
class.cs

namespace App{
      class className{
              private void method(){MessageBox.Show("No Record To Export", "Info");}
      }
}

CodePudding user response:

If you just want put some code in a function, you should declare the function like

public static class MyClass{
      public static void MyMethod(){...}
}

If you only need the method from within the same project you can replace public with internal.

A static method is appropriate if the method only depends on the given parameters, if it needs to maintain a state you need to remove the static, create an object of the class in your form, and use that object to call the method.

CodePudding user response:

If you want to separate different layers of an app, I suggest you use a design pattern like MVVM. This way you would have classes that does the functionality of the app and other classes work with database and so on.

  •  Tags:  
  • Related