简体   繁体   中英

.NET C# - Form versus Designer code files for Event Wiring

I was just curious how others work with this kind of WinForm code in C#. Lets say I have a Form lets 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 the Form1 code or the Form1 designer code? Should this "event wiring" code go in the Form1_Load method?

The reason I am ask 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 designer code. Should your "event wiring" code be in two places?

Short answer is yes.

Longer answer is that .designer.cs is there for code generated by the designer. if you put your own code in there, it has a chance of getting overwritten, screwing up the design time stuff in visual studio, and lowers maintainability because nobody expects custom code to be in there.

This is a touchy subject. In 1.1, there where regions for this in your forms file, but a lot of the time, the code would be over written by the designer. I'm speaking from webforms experiance, but I would only gather that it would be the same elsewhere.

Now, you actually put the eventname in the form itself (it's one of the properties on the forms designer), and the code generator will push out the += event handler thingies in the partial class. I hate it this way, but it is what it is.

I use the Designer for all event related to Component.

I use the code for all object event.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM