How do I add Dispose functionality to a C# UserControl?

女生的网名这么多〃 提交于 2019-11-29 23:09:50

In such a case I move the generated Dispose method to the main file and extend it. Visual Studio respects this.

An other approach would be using a partial method (C# 3.0).

All Component classes implement a Disposed event. You can add an event handler for that event and clean up things in there.

For example, in your UserControl you could add following method:

private void OnDispose(object sender, EventArgs e)
{
    // do stuff on dispose
}

And in constructor (or in Load event handler) add the following line:

Disposed += OnDispose;

I believe in this case the code-generator honors your code. It should be safe to put it in the codebehind.

In VS 2005 (and 2008) you can update the Dispose method and it will not get removed when you edit the control from the designer.

You can move it out from the .designer.cs file and into the main .cs file if you want. As has been said already, it won't be overwritten.

You just need to overload the public void Dispose() method in the Component Class that the user control inherits.

make sure you pass the call to the base method as well as doing your dispose functionally or you'll break the functionality unless you fully implement it

I would think the cleanest way would be to have your control subscribe to its own Disposed() event and do your cleanup in there.

there is a Unloaded event for the UserControl that you can use to clean up,

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