mihocu
mihocu

Reputation: 65

windows forms organize code

Okay, so this is my first windows forms app and I'm facing some difficulties re-structuring my code. started off putting everything in the Form1 class that provided by default, it has grown too large quickly. I'm aware this is a pretty bad programming practice so I started some clean up and made different classes to satisfy single responsibility principle. however, as some button-related and grid-related events are working well in the Form1 class, taking them outside makes them crash and I'm clueless how it should be done.

public partial class Form1
{


    public Form1()
    {
        InitializeComponent();

    }

    private void method1(object sender, EventArgs e)
    {
            //CODE
    }



    private void method2(object sender, DataGridViewCellEventArgs e)
    {
           //CODE
    }



    private void method3(object sender, EventArgs e)
    {
          //CODE
    }

}

so I'd like to move method1, method2, method3 etc to a different class (or different classes), but pretty much lost with how to do this without breaking the app. well, private is obviously set to public to grant access but I have no idea how to call these methods afterwards in Form1 class. when I created new classes and then tried to call the methods on event, like onClick: Newclass.method1() it didn't work. one thing I could think of is like calling some method in Form1 onClick: thisMethodCallsTheOneINeedInADifferentClass(), but this seems to be a clumsy solution... I'm sure there are better ways to sort this out I just don't know how to. Advice appreciated, thank you

Upvotes: 5

Views: 1464

Answers (2)

nicoh
nicoh

Reputation: 394

You should keep the event handlers in the Form, but you can move the code to another class. If you want to call your class you cant directly call it. You need to do something like this:

YourClass class1 = new YourClass(); 

You can also declare it static then you only need to call it once.

private static YourClass class1 = new YourClass();

Then you can use your method like this:

class1.YourMethod();

Upvotes: 4

EJC
EJC

Reputation: 2141

Those are the event handlers for the button events. If you want to have the method specified elsewhere, you'll have to wire the event handler up manually in your code behind.

The code for the wire up right now is in the designer file, you'll see something like:

button1.Click += new System.EventHandler(method1);

I'd say it's ok to have the event handler be in the code behind and just call some sort of rules method from another class that you have written elsewhere. There's no shame in having SOME code live in the code behind.

At the end of the day the designer has to point to the correct event handler and if you move it out of the Form1.cs class, you'll have to point it at the correct place.

Upvotes: 0

Related Questions