Answered Split the main form into smaller files

MakeItWork

Member
Joined
Feb 20, 2021
Messages
6
Programming Experience
1-3
Hi all,

Hopefully this question is not to stupid so here we go.....
With c# window forms the main code starts with

public partial class Form1 : Form

I have been splitting the main code file into separate files that still compile into one with

public partial class Form1

It works but does not appear to like any other visual studio than the one it was set up in and the project file can corrupt easy.
I think it is the cause of other problems like Graphics .invalidate which has never worked. Windows size adjustment of the program being run does not change to the value it is set to. Int16 (short) conversion/use has caused errors with nothing wrong with the code. Picturebox code would not work (no compile errors) until it was moved to another location, nothing wrong with its original location and now graphics code doing the same.

I Googled the problem which gives no end on how to split classes, it is not clear how to split the main form.

How wrong is splitting code up using public partial class Form1 and what is the correct way.

Thanks in advance
 
Solution
As you can see in documentation inheritance and implemented interfaces are merged, you don't have to repeat this information in each file, and you can spread it across the files (see the article for example).

Don't try to design the partial files except the default one, or else designer will attempt to add designer code twice, which won't work. If you for example try to add a control to the extra partial class the designer adds InitializeComponent and more that conflicts.
Change the filename of added partial files to Form1.yourNameHere.cs

This stops the problem with a design window being attached to each added partial file.
Microsoft have in there wisdom made all added partial main code files without the usual editor support, all...
I can't believe I actually approved this topic. :LOL:

Well, I'm looking forward to the replies. lol

And, welcome to the forums.
 
Except for the problem about Visual Studio WinForms Designer having issues with splitting up the form code into multiple files, all your other problems have nothing to do with splitting the files. Consider the fact that by default Visual Studio already used partial classes to separate your code from the designer generated code in the Form.Designer.cs file. People have successfully used WinForms for years with that file configuration. I suspect those other problems are due to bugs in your code, or not fully understanding how some things work.

Personally, I don't use the WinForms Designer, so it doesn't matter that I use partial classes often without ill effects. On the other hand, I rarely have to split up my Form class into multiple files because I apply the MVC or MVP pattern to my code. So my Form code (aka View) tends to be just thin layers that call the Model and/or the Controller or Presenter.

Why don't you show us some of the code that you are running into problems with and we can try to get you sorted out.
 
Is there actually a logical reason for doing this? ?

And if there is, when would you want to?

I here you all the way regarding the designer code. Me and you have been on that same page now for many years.
 
Yes, there are some logical reasons to do this, but usually it is when you are creating a new control from the ground up, not when you are writing a form -- unless the form doesn't follow the Single Responsibility Principle.

Anyway, check out the source code for the DataGridView control on Reference Source to see a control that has been split up into multiple files. As I recall, each file followed the SRP, but due to the constraints of WinForms, all that had to live within a single class.
 
The WinForms designer will expect two partial class files. Form1.cs is where it will create event handlers that you generate from the Properties window and Form1.Designer.cs is where it will declare, create and configure controls and components you add in the designer. As long as those two files are present with a partial Form1 declaration in them, the designer is happy. Other than that, you can add as many other code files with partial Form1 declarations in them as you like and they will all function as a single class. I've tested this and it seems to work without issue, but I obviously haven't tested every possible combination.

As you should ALWAYS do, you need to show us the code. You should provide the minimum amount of code necessary for us to understand and reproduce the issue. If we see the code then we can see what you may have done wrong and, if you haven't, see whether we get the same aberrant behaviour using the same code.
 
By all means single me out here.

But there are very very very few valid reasons for doing something like that. I honestly was anticipating more scepticism from senior devs here.

And I can't help but feel doing something like this is quite illogical???
 
For ASP.Net or something, yea, I can see the point of partial views, and segregating views but I don't see the need when it comes to Winforms.
 
By all means single me out here.

But there are very very very few valid reasons for doing something like that. I honestly was anticipating more scepticism from senior devs here.

And I can't help but feel doing something like this is quite illogical???
Personally, pretty much the only time I use partial classes is when I want part of the code to be auto-generated and part of the code to be user-editable, much like the split between designer code and user code in a form. For instance, I've just been updating our CodeGen tool at work for .NET 5.0 and EF Code First. We use this tool to generate various sets of files where there is one per entity, including DTOs and services. The service definitions are always in partial classes because we have a standard set of methods that get auto-generated in one partial class and we can add entity-specific methods in a second partial class.

If you have a class that contains a lot of code then regions should probably be the first option for grouping code relating to a specific area of functionality but partial classes might be a good option if the volume of code is very large. The DataGridView example from before is one such but I would suggest that most classes, be they forms or otherwise, that contain enough code to make partial classes a good option are probably poorly designed and out to be split into multiple distinct classes anyway.

That said, we can't all learn everything at once and coming to terms with the current issue may help the OP learn something else, given that they believe that partial classes are causing other issues that they definitely should not be.
 
I was expecting this to be more or less straight forward lol.
Yea, what i am thinking is the same as in C++ with separate files, this makes editing and organising your code easier, it stops one file becoming large in size. I suspect it is easy to do when you know how.

I find microcontroller assembler simple and straight forward and i am learning c# with the same approach by avoiding a lot of the correct terminology and stuff i don`t think i need to know....trying to keep it simple, does that show? Lol. c# is a bit of fun like doing a crossword puzzle and usefull if i need to write software to interface a electronic project.

The only way to give a example is upload the entire project file, the file almost certainly will not load into any other editor (uses vs2019) becouse of the way the files have been separated but we shall see. Any thoughts/advice before i upload?

"Sheeping" "I honestly was anticipating more scepticism from senior devs here.", i am trying to make the code easier to read and edit by splitting a large file into smaller files, same as you can in C++, what do you think i am trying to do???
 
I know what you are trying to do. I just don't see the logic in the way of how you are going about it, and especially in Winforms.

And C++ is not C# either.

As I've often seen in the past, Skydiver telling people to ditch what they know in the way of C++ when moving to do things in C#.
 
I suspect that @Sheeping's expectation was based on most senior devs would not let a single class grow that large that if would need to be split into multiple files to help the humans organize the contents of the class better.

When I do code reviews for peers, if the file size exceeds 600 lines, it is a code smell for me that perhaps the class within the file may not be following the SRP, and so should be broken up to make use of separate helper classes which can then be tested independently.

And yes, implementing object oriented programming in C++ is slightly different than implementing object oriented programming in C# because of different idiomatic uses, and different expectations for each language.
 
I can't preach about rules/principles and laws which should be kept, and then go off and break them myself. That's just stupid and hypocritical of me.

The other day I binned an entire application because a helper class exceeded 800 lines. Once again Skydiver makes a good point about SRP, and how you should apply it when writing an app. Regarding your initial issue, I wouldn't look any further than post 9, on the very last line.

Frankly, if you are writing a to a file that requires that a class must have a lot of functions, methods, or a very long and elaborate task/operation to execute, then you are likely not writing efficient code. Code that should have one single purpose to fulfil.
 
Hi everyone, i would like to start again with a different approach as i feel there is a simple answer to this, i may be wrong of course.

We have a simplified code example below, it is only to show what i want it will not run.

C#:
using System;



namespace game

{

    public partial class Form1 : Form
    {
    //All your normal code when you double click on the design window in c# dotnet framework
    }

// Here we will put in some code, a function called PicBox, for example only.

       public void PicBox()
        {
            PictureBox[] picture = new PictureBox[(picRow * picCol)];
            int i;
            for (i = 0; i < picCol * picRow; i++)//(picRow * picCol); i++)
            {
                picture = new PictureBox();
                picture.BackColor = Color.Black;
                this.Controls.Add(picture);
                picture.Click += this.pb1_MouseClick;
                picture.SizeMode = PictureBoxSizeMode.StretchImage;
                picture.Visible = true;
            }
            picbox = picture;
    }

I would like to put the function PicBox into a seperate file, a separate window in visual studio that only needs to be clicked on if i want to edit the function PicBox, this is to help reduce clutter and make the code neater for me, basically it makes me happy.

To select a new class file in VS is ok for some types of code but to access windows functions can sometimes be more work than it is worth or not possible, i think i am correct in saying that.

I think i need to extend the first line of code given in a new project which is:
public partial class Form1 : Form

I am missing some of the basic understanding here.

If anything is not clear please ask, i am sure there is a simple answer to this.

Thanks in advance
 
Last edited by a moderator:
Back
Top Bottom