Several times throughout the course of our current project, the visual studio designer has made modifications that resulted in losing code. For example, event handlers wirings that were set up manually in the designer code were lost. Does anyone know why this happens?
Edit: I understand that editing these开发者_JAVA百科 files manually is not a good idea, but it has also happened with other event wirings set up through the designer.
Well for starters read the XML at the top of your designer.cs file.
/// <summary>
/// Required method for Designer support - do not modify
/// contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
Generally you shouldn't be modifying these files as they are auto-generated. It's probably the reason why there is a slight attempt to hide the code within a branch, underneath the main partial class.
I have on occasion found that the process has removed its own auto-generated code that I've had to merge back in. Most commonly it decides it's not going to instantiate custom user controls anymore, so when I start running I get a NullReferenceException.
Really the answer is to put the code somewhere else, like in the constructor before calling the InitializeComponent() method. If fellow developers aren't aware of this, then you should inform them and educate them, the fact that the files are .designer.cs should raise questions even to newer developers as to why the strange extension.
You guys aren't modifying generated code files, are you? Like MyForm.Designer.cs
? This is why we were given partial
classes.
Because it is designer generated and more or less maintained code. It is recommended that you not add or modify code in the designer partial class manually exactly because of the behavior you described (I think it even mentions this in the generated file itself). If you need to wire up event handlers manually then do it in your custom code possibly the constructor of your control.
Write all necessary initialization code only in your own .cs file, you have number of places to do this, like form constructor and form Load event handler.
Moving the designer code into user maintained code classes defeats the benefits of being able to modify the user interface. Perhaps this might be something you would want to do if the program never needs to be modified again, but if that is the case... where is the benefit as well?
This issue of the designer class losing lines of code has existed since Visual Studio was initially released and has caused me countless nightmares because the loss occurred perhaps weeks before, when the program was previously modified.
I can't prove it but it seems obvious that something in Microsoft's code generator is failing and there isn't any alerts to tell you it crashed. So, Microsoft... fix what is crashing or at least, tell us about it when it happens.
精彩评论