WinForms control event handler gets removed when selecting another one and thus it becomes 'unreferenced'
Question about the WinForms designer and how to customize behavior. What I've seen multiple times is that when you select a different event handler for a button it w开发者_如何学运维ill remove the old one (as in ,the code) when it becomes unused.
I want to avoid this behavior but can't find configuration for this. Anyone a hint? Thanks!
Update Since multiple comments question the actions that trigger this in the first place, I'd like to point out that it has mostly hit me during refactoring of an existing code base.
There is no configuration for this. The designer does the Right Thing, it only removes event handlers that have no code. As soon as you put something in the method body then it preserves what you've written and generates a new method. This ensures that you don't lose code and ensures that you don't have dead methods littering your code.
Beware that adding more than one event handler for a control's event in the same class (form) makes very little sense. You should just merge the code of the handlers. This also ensures that you won't have any surprises, the order in which multiple subscribers for the same event runs is fairly unpredictable. The designer only supports a single event handler, simply because it doesn't have any way to track more than one.
This is just the way the Designer works - you can't change it.
What you can do to work around your problem is to add your event handlers in code, rather than in the designer:
public Form1()
{
InitializeComponent();
this.button1.Click += new EventHandler(button1_Click);
this.button1.Click +=new EventHandler(button1_Click2);
}
I must point out that I question the need for two separate event handlers.
精彩评论