473,597 Members | 2,839 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dispose for UserControl

Hi,

I have a UserControl (C# WinFroms application) that requires some cleaning
code to run when a form with control is closed. Where I can put that code?

There is no ControlClosing or ControlClosed event.
I can put my code into UserControl.Des gner.cs Dispose method, but that seems
to be a bad practive.

What do I do?

Thanks.

Jun 27 '08 #1
6 23340
Don't modify the designer files if you can help it. If the file changes a
lot of times the designer will overwrite any work you've put into the files
if it needs to change that piece. That's why the designer files say to not
modify them and why partial classes are so good. :o)

In your control, override the Dispose(bool) method and handle your cleanup
there. You'll want to make sure you only handle the disposal when disposing
is true, false gets passed to the method when the destructor gets called by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null. Then, in
your form's closing event, simply call the Dispose() method on your user
control.

Also, about disposal of private objects - generally speaking, I tend to only
implement IDisposable when the private fields of a type implement
IDisposable themselves.

"Victor" <Vi****@discuss ions.microsoft. comwrote in message
news:D3******** *************** ***********@mic rosoft.com...
Hi,

I have a UserControl (C# WinFroms application) that requires some cleaning
code to run when a form with control is closed. Where I can put that
code?

There is no ControlClosing or ControlClosed event.
I can put my code into UserControl.Des gner.cs Dispose method, but that
seems
to be a bad practive.

What do I do?

Thanks.
Jun 27 '08 #2
Jeff,

thanks for you answer.

I can not override Dispose(bool disposing) in my code, since it has been
already 'overridden' in UserControl.Des igner.cs autogenerated file.

Any attempt to override it again in UserControl.cs results in a compilation
error.

Victor

"Jeff Winn" wrote:
Don't modify the designer files if you can help it. If the file changes a
lot of times the designer will overwrite any work you've put into the files
if it needs to change that piece. That's why the designer files say to not
modify them and why partial classes are so good. :o)

In your control, override the Dispose(bool) method and handle your cleanup
there. You'll want to make sure you only handle the disposal when disposing
is true, false gets passed to the method when the destructor gets called by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null. Then, in
your form's closing event, simply call the Dispose() method on your user
control.

Also, about disposal of private objects - generally speaking, I tend to only
implement IDisposable when the private fields of a type implement
IDisposable themselves.

"Victor" <Vi****@discuss ions.microsoft. comwrote in message
news:D3******** *************** ***********@mic rosoft.com...
Hi,

I have a UserControl (C# WinFroms application) that requires some cleaning
code to run when a form with control is closed. Where I can put that
code?

There is no ControlClosing or ControlClosed event.
I can put my code into UserControl.Des gner.cs Dispose method, but that
seems
to be a bad practive.

What do I do?

Thanks.

Jun 27 '08 #3
Oops, I didn't realize the designer overrides the method. Makes sense though
considering it's a container for other controls. Perhaps rethinking the
design would be useful so you aren't having to dispose of the object from
the control. However, that method should be fine if you moved it out of the
designer and into the code file for the control.

"Victor" <Vi****@discuss ions.microsoft. comwrote in message
news:AA******** *************** ***********@mic rosoft.com...
Jeff,

thanks for you answer.

I can not override Dispose(bool disposing) in my code, since it has been
already 'overridden' in UserControl.Des igner.cs autogenerated file.

Any attempt to override it again in UserControl.cs results in a
compilation
error.

Victor

"Jeff Winn" wrote:
>Don't modify the designer files if you can help it. If the file changes a
lot of times the designer will overwrite any work you've put into the
files
if it needs to change that piece. That's why the designer files say to
not
modify them and why partial classes are so good. :o)

In your control, override the Dispose(bool) method and handle your
cleanup
there. You'll want to make sure you only handle the disposal when
disposing
is true, false gets passed to the method when the destructor gets called
by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null. Then, in
your form's closing event, simply call the Dispose() method on your user
control.

Also, about disposal of private objects - generally speaking, I tend to
only
implement IDisposable when the private fields of a type implement
IDisposable themselves.

"Victor" <Vi****@discuss ions.microsoft. comwrote in message
news:D3******* *************** ************@mi crosoft.com...
Hi,

I have a UserControl (C# WinFroms application) that requires some
cleaning
code to run when a form with control is closed. Where I can put that
code?

There is no ControlClosing or ControlClosed event.
I can put my code into UserControl.Des gner.cs Dispose method, but that
seems
to be a bad practive.

What do I do?

Thanks.
Jun 27 '08 #4
Thanks Jeff,

Moving the method out of the designer file solves my problem.

Victor

"Jeff Winn" wrote:
Oops, I didn't realize the designer overrides the method. Makes sense though
considering it's a container for other controls. Perhaps rethinking the
design would be useful so you aren't having to dispose of the object from
the control. However, that method should be fine if you moved it out of the
designer and into the code file for the control.

"Victor" <Vi****@discuss ions.microsoft. comwrote in message
news:AA******** *************** ***********@mic rosoft.com...
Jeff,

thanks for you answer.

I can not override Dispose(bool disposing) in my code, since it has been
already 'overridden' in UserControl.Des igner.cs autogenerated file.

Any attempt to override it again in UserControl.cs results in a
compilation
error.

Victor

"Jeff Winn" wrote:
Don't modify the designer files if you can help it. If the file changes a
lot of times the designer will overwrite any work you've put into the
files
if it needs to change that piece. That's why the designer files say to
not
modify them and why partial classes are so good. :o)

In your control, override the Dispose(bool) method and handle your
cleanup
there. You'll want to make sure you only handle the disposal when
disposing
is true, false gets passed to the method when the destructor gets called
by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null. Then, in
your form's closing event, simply call the Dispose() method on your user
control.

Also, about disposal of private objects - generally speaking, I tend to
only
implement IDisposable when the private fields of a type implement
IDisposable themselves.

"Victor" <Vi****@discuss ions.microsoft. comwrote in message
news:D3******** *************** ***********@mic rosoft.com...
Hi,

I have a UserControl (C# WinFroms application) that requires some
cleaning
code to run when a form with control is closed. Where I can put that
code?

There is no ControlClosing or ControlClosed event.
I can put my code into UserControl.Des gner.cs Dispose method, but that
seems
to be a bad practive.

What do I do?

Thanks.

Jun 27 '08 #5
In your control, override the Dispose(bool) method and handle your cleanup
there. You'll want to make sure you only handle the disposal when disposing
is true, false gets passed to the method when the destructor gets called by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null.
Hi Jeff.

Are you sure about this? Its my understanding that even if the
finalizer is being called by the garbage collector you are still able
to get a handle to the other child objects.

Of course, referencing a child object while the garbage collector is
disposing of them may be a bad idea because the object that you are
calling may have had their Dispose method already called but that
should be another story.

I put together a little sample to test this, if you run the sample
below, even if “ChildClass” get dispossed first, “ParentClass” is
still able to successfully get a reference to the “ChildClass”.

namespace ConsoleApplicat ion393
{
class Program
{
static void Main(string[] args)
{
ParentClass m = new ParentClass();
}
}

public class ParentClass
{
ChildClass m_Caca = new ChildClass();

public ParentClass()
{

}

~ParentClass()
{
// No problems here even if "ChildClass " has been
disposed.
int o = m_Caca.SomeInt;
}
}

public class ChildClass
{
public int SomeInt = 123;

public ChildClass()
{
}

~ChildClass()
{
SomeInt = 999;
}
}
}

Is that what you meant?

Thanks.
Jun 27 '08 #6
It depends on how the class you're using implemented the IDisposable
interface. Below is an example of how I typically implement the interface.
The problem when relying on the destructor to clean up your object when
using child objects that implement the IDisposable interface - they may have
already been disposed of by the time the destructor on your class gets
called. Which is why whenever an object implements IDisposable you're
supposed to call Dispose on your own when you're done with it to ensure
everything within the object gets cleaned up properly.

As for your example below, we were talking about the use of IDisposable -
not whether you can access child objects from an objects destructor.
Implement IDisposable in both of your classes, call dispose on the parent
object and then let the destructor try and access it. It should throw an
exception about trying to use an object that's already been disposed of.

static class Program {
static void Main(string[] args) {
using (DisposableObje ct o = new DisposableObjec t()) {
o.DoWork();
}
}
}

class DisposableObjec t : IDisposable {
Stream _s;

public DisposableObjec t() {
this._s = new MemoryStream();
}

~DisposableObje ct() {
this.Dispose(fa lse);
}

public void Dispose() {
this.Dispose(tr ue);
GC.SupressFinal ize(this);
}

public void DoWork() {
}

void Dispose(bool disposing) {
if (disposing) {
this._s.Dispose ();
}
}
}

<qg**********@m ailinator.comwr ote in message
news:ff******** *************** ***********@2g2 000hsn.googlegr oups.com...
In your control, override the Dispose(bool) method and handle your cleanup
there. You'll want to make sure you only handle the disposal when
disposing
is true, false gets passed to the method when the destructor gets called
by
the garbage collector. In which case if it is false, the objects you're
trying to clean up have already been released and will be null.
Hi Jeff.

Are you sure about this? Its my understanding that even if the
finalizer is being called by the garbage collector you are still able
to get a handle to the other child objects.

Of course, referencing a child object while the garbage collector is
disposing of them may be a bad idea because the object that you are
calling may have had their Dispose method already called but that
should be another story.

I put together a little sample to test this, if you run the sample
below, even if “ChildClass” get dispossed first, “ParentClass” is
still able to successfully get a reference to the “ChildClass”.

namespace ConsoleApplicat ion393
{
class Program
{
static void Main(string[] args)
{
ParentClass m = new ParentClass();
}
}

public class ParentClass
{
ChildClass m_Caca = new ChildClass();

public ParentClass()
{

}

~ParentClass()
{
// No problems here even if "ChildClass " has been
disposed.
int o = m_Caca.SomeInt;
}
}

public class ChildClass
{
public int SomeInt = 123;

public ChildClass()
{
}

~ChildClass()
{
SomeInt = 999;
}
}
}

Is that what you meant?

Thanks.

Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4012
by: Rhy Mednick | last post by:
I'm creating a custom control (inherited from UserControl) that is displayed by other controls on the form. I would like for the control to disappear when the user clicks outside my control the same way a menu does. To do this my control needs to get notified when the user tried to click off of it. The Leave and LostFocus events of the UserControl work most of the time but not always. For example, if they click on a part of the form...
2
8298
by: Jaikumar | last post by:
Hi, 1) I have created one windows application, In the main form ( form1) i have added one usercontrol (usercontrol1), In that user control i am drawing one image. 2) In the UserControl1 i am showing one transparent form (form3) when ever user preseed left mouse button. 3) The form3 has one transparent user control (usercontrol2) that paints circles. That measn the circles will show on top the usercontrol1 image. 4) The form3 border style...
1
28310
by: MuZZy | last post by:
HI, I have a user control, say with one textBox. I need the following: when the user closes form (either calling Form.Close, or pressing "X" or anyhow), UserControl copies a file from a predefined folder to a folder in the textBox. UserControl doesn't have a "Closing" event, so i tried to override UserControl.Dispose() : // ========================================================== protected override void Dispose( bool disposing )
9
20148
by: Charles Law | last post by:
I have a form on which user controls are placed at runtime. When a control is added to the form a handler is added for an event that a high-level object raises, which must be handled by the new control. When I close the form I am expecting that the control ceases to be. However, if my object raises the event after the form has been closed, I find that there is still a user control object that handles it. Clearly the user control has not...
0
2458
by: Matthew | last post by:
All, I have searched google and the newsgroups but can't find anything the same as what I am experiencing (though I may have missed something). I have controls (textboxes) within UserControls which are not behaving as I would expect. Specifically, if there is a command button external to the usercontrol which is activated by a shortcut key (eg Alt-B), the command button Click event handler code 'executes' even though the textbox set...
0
2429
by: Gary Shell | last post by:
I am experiencing some strange behavior between a UserControl's validating event and a treeview control. Initially, I thought it was related to an issue in the Knowledgebase article 810852 (http://support.microsoft.com/kb/810852), but then I realized that the hotfix mentioned was in .Net v1.1, which I am using. I took the sample from that article and recreated the situation I see in my application. (Code included below.) If you run the...
7
5332
by: Peter Proost | last post by:
Hi group, Here at work they've got an activeX control which is used on a usercontrol, and this usercontrol is one of the standard controls in the framework, so this user controls get's used a lot on other usercontrols or windows forms. But the problem is the activex control doesn't get disposed. (profiled the app with scitech .net memory profiler 2.5) I added this code to disposing event of the base usercontrol (the one in the framework...
2
5051
by: Steve | last post by:
This is a weird one. I have a series of "SmartParts" which are CAB (Composite Application Block) Views which are finally just UserControls (99% of the time) Anyway, I layout my UserControl in the VS2005 designer, but at runtime, the controls are in different locations and different sizes. I have been able to restore their sizes by putting a hack together that will set their sizes to the correct values in the UserControl's Resize...
4
2460
by: Martin | last post by:
Hi everyone ! For those who haven't read my previous post, I have a problem with a UserControl. When I try to display it on a form, controls seem to appear one after one. In the following example, it's less visible because controls don't execute any code... Is someone has an idea of how I could solve this problem and also improve the method ShowUserControl. I try to figure out I could flicker effect when I press the button twice quickly.
0
7967
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7885
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8381
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8031
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
5847
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5428
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3882
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3923
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1493
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.