I have a form with 3 tab controls on it, and each tab control has a dozen or so text fields. Right now I have all of my methods for modifying the text fields within Form1.cs, which is working, but is a very long class. I am curious if it is propper method to keep methods that call Form controls within that forms class, or if you should divide them out into other classes? I read this thread and I may be confused, but it sounds like the chosen answer is saying you should not try to access form controls from other classes? How to access form methods and controls from a class in C#?
4 Answers
The best method for encapsulation in this scenario is to create user controls that contain the text fields for each tab. Then, each tab just has a user control on it, and all the logic specific to those fields is encapsulated in its own control.
2 Comments
It's easily done, you just pass a reference to the form to the other class, but then they become tightly coupled and therefore fragile.
A better option would be to define an interface and have the form implement it, that can get messy though.
Other options would be move the controls on your tab to a user control or even just another form and then host them in your main form's tabs. Then you could isolate the data and operations of each tab. Again defining and implementing an interface or two will help you decouple.
Think of it this way, you separated out the UI in to tabs, there is some underlying logic behind that from a UI point of view so it follows, there should be some logic in terms of separating the functions the controls on the tabs perform. I have seen exceptions to that, but it was usually because the separation in the tabs had no logic at all.
Comments
There are different ways to organize applications. It is usually a thing to separate the GUI (the forms) from the other application logic. Do only display logic in the forms. Create data classes (also called models) for you data. You might want to have classes like Customer, Order, Address and so on. These classes contain the "business logic", e.g. the Order class knows how to calculate the taxes, not the order form.
You can save you a lot of effort by using data binding to bind your business objects to the forms. See my SO answer for the use of data binding.
You can go even further by separating the logic into three parts by using the MVC pattern. I am not going to explain it in detail here. Just this, MVC stands for Model View Controller. Model is the business class, View is the form and Controller is a class that manages the model and the form, loads and stores the model etc.