user2635088
user2635088

Reputation: 1618

Editing the InitializeComponent() method C#

I've gone through multiple resources on trying to find the use cases of when to manually add code to InitializeComponent, but haven't found anything concrete. This suggests we shouldn't do it - The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified

In the past, I had always used the form designer and never needed to manually make changes to InitializeComponent(). However at my new firm, the tech lead has completely ignored the form designer and manually added most UI elements within InitializeComponent (i.e. it has either been heavily edited, or completely re-written to the extent that the Designer can't recreate the GUI in VS, but the GUI is visible and fully functional at when the code is executed)

What is the advantage of not using the form designer? Is it just a matter of preference? Is manually editing/rewriting InitializeComponent for simple UI elements a good practice?

Thanks!

Upvotes: 4

Views: 5543

Answers (1)

tremas317
tremas317

Reputation: 81

There are only a few reasons why one might need to edit InitializeComponent, such as:

  1. To correct bugs introduced by a bad toolbox item designer.
  2. To remove all traces of a control that cannot be deleted from the VS designer. (This has to be done carefully.)
  3. To make quick "designer friendly" tweaks: changing a property value, adding a property setting, or removing a property setting. When adding a setting, I make sure it looks just like the designer-generated code.

After editing InitializeComponent, I always save & switch back to Designer mode to make sure I didn't break anything.

Any manual initialization code should be added outside InitializeComponent, e.g. OnLoaded() in a WinForms form or user control. As for fixing existing forms, it may be simple or nearly impossible depending on how complicated the form is, especially if controls have been added manually and required initialization methods (such as SuspendLayout, BeginInit) aren't being called.

Upvotes: 4

Related Questions