Add/Remove handler to textbox

做~自己de王妃 提交于 2019-12-04 04:17:57

It is good, but you dont need to remove the handler, and adding the handler just put this:

tb1.KeyDown += TextBox_KeyDown;

because new KeyEventHandler(TextBox_KeyDown); is redundant.

Your approach is fine. In both the addition and removal of the event handler delegate, you can omit the new KeyEventHandler and surrounding parenthesis around TextBox_KeyDown. These are implied by the compiler (so long as the TextBox_KeyDown method has the expected signature). This is purely a matter of preference of course.

Yes, that is entirely correct. However you can use the shorthand notation:

tb1.KeyDown -= TextBox_KeyDown;

Although the effect is exactly the same.

However, it is worth determining whether you really need to remove your event handler? What is the lifecycle of your form and the TextBox? if the form 'owns' the TexBox, i.e. it is longer lived, then you do not need to remove the event handler.

To remove the event handler you should just do:

tb1.KeyDown -= TextBox_KeyDown;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!