.NET C # - Form and Designer Code Files for Posting Events

I was just wondering how others are working with this WinForm code in C #. Let's say I have a form that allows me to call it Form1. And I have a DataGridView called dgvMain.

Where do you put the code:

this.dgvMain.CellEndEdit += new DataGridViewCellEventHandler(dgvMain_CellEndEdit);

      

Do you put it in Form1 code or Form1 constructor code? Should this "event posting" code go in the Form1_Load method?

The reason I'm asking is if you double click the DataGridView the IDE inserts the code:

 this.dgvMain.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvMain_CellContentClick);

      

into the constructor code. Does your "event posting" code have to be in two places?

0


source to share


3 answers


The short answer is yes.



The longer answer is that .designer.cs exists for designer generated code. if you put your own code there, it will have the ability to be overwritten, spin design-time stuff in visual studio and reduce maintainability because no one expects custom code to be there.

+2


source


This is a touchy subject. In 1.1, where the regions for this are in your form files, but time consuming, the code will be written by the designer. I am speaking from webforms experiance, but I would only understand it would be the same elsewhere.



Now you are actually putting the event name on the form (this is one of the properties in the form's constructor) and the code generator will push the event handler objects + = in the partial class. I hate it this way, but this is what it is.

+1


source


I use Constructor for all component related events.

I am using code for all object events.

0


source







All Articles