In C#, how can you easily change the name of an event handler?

淺唱寂寞╮ 提交于 2019-12-05 18:15:32

When you rename the control, you should rename the event handler too. The proper way to do this is by refactoring the code.

To do this, just right-click the name of the event handler in the Visual Studio code editor and choose Refactor -> Rename... That will allow you to automatically change the name of it everywhere it's used.

In the case of an event handler, it's probably only used in one other place (the point in code where it's added to the event), so it's not too much trouble to change it manually. You can apply this technique to pretty much anything, though, making it extremely useful when something you're changing is referred to from several different places.

You just have to find the place in the generated code where the combobox1_SelectedIndexChange method is declare and change the name to cbStatus_SelectedIndexChange.

After you change the method name, you also have to update the line where you register the handler:

cbStatus.SelectedIndexChange += new
    SelectedIndexChangeEventHandler(cbStatus_SelectedIndexChange);

Just type the new name, then recompile. By this I mean - Change

protected void combobox1_SelectedIndexChanged(object sender, EventArgs e)
{

}

to

protected void renamedcombobox_SelectedIndexChanged(object sender, EventArgs e)
{

}

and then recompile

Visual Studio will throw a compile-time error, because the method that is expected is no longer there.

Double-click on the error in the Output window to go to the assignment of the error handler, and change the error handler there to match the new function name.

Edit - added

The above step will jump you to the line of code described in Justin's answer...

End Edit

I know that's clear as mud, but try it and you'll figure it out with little or no difficulty.

If you single-click instead of double-clicking to automatically create the event handler, you can specify the handler name you want. You could make it something like "SelectedStatusChangedHandler", which is independent of the combobox's variable name. Then press 'enter' and let VS create the handler for you.

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