Forum; I am a newbie working out a bit of code. I would like to know the best way to use separate .cs files containing other classes and functions. As an example of a basic function would would like to click on a clear button and have it clear all fields on a form. The code is split up into three .cs files. Main.cs, MainForm.Designer.cs and btClear.cs.
MainForm.Designer.cs contains the designers automatically created code including the Clear Button, and the text boxes I would like to clear.
I would like to have the code to clear the text boxes contained in btClear.cs. I understand it would be easy to simply to place this code in MainForm.Designer.cs however I would like to use this as a template in order to use separate .cs files as a standard practice.
Can someone give me an example of how to do this please?
The way most .net programmers would do it is:
MainForm.cs, but declare a new method for separating the code that does the clearing.I always leave in the event handler method (the one VS generates when you double-click the button) code to change the mouse cursor (in case the code I’m calling takes a couple of seconds or more to run) and catch all unhandled exceptions, and put my logic in a separate private method:
In my opinion, if you want to follow the conventional way of doing things in .net, you should stick with this first example.
Moving code out of the form .cs files is recommended when the code is not part of the form logic, for example, data access code or business logic. It this case I don’t think that clearing the form controls qualifies as business logic. It is just part of the form code and should stay in the
MainForm.cs.But if you really want to put the
ClearFormmethod in another .cs file, you could create a new class and move theClearFormmethod there. You would also need to change the Modifiers property of each control to Public so your new class can have access to them from outside MainForm. Something like this:You would have to change the main form code to:
But note that your
FormCleanerclass would have to know about yourMainFormclass in order to know how to clear each of the controls of the form, or you would need to come up with a generic algorithm that is able to loop through theControlscollection of any form to clean them:And as others have said,
MainForm.Designer.csis machine-generated and you should never put your own code there.