Event Handlers

J

Jake K

Where is the best place to define event handlers? I need to define event
handlers for a COM object referenced in my project and am doing so in the
fowm load. Is this the best place?
 
M

Michael Nemtsev

Hello Jake,

In asp.net the general place for event handlers is Page_Init, but it's common
for the page controls
In your case you can put defining there.

I don't think that the Page_Load is really the best case, because you need
to check whether it's postbacked or not

JK> Where is the best place to define event handlers? I need to define
JK> event handlers for a COM object referenced in my project and am
JK> doing so in the fowm load. Is this the best place?
JK>
---
WBR,
Michael Nemtseva [C# MVP] :: blog: http://spaces.live.com/laflour

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangel
 
J

Jake K

Thanks for the reply.

I forgot to mention that I am building a Windows Forms project that will
eventually become a service. Where would the best place be in this case to
define event handlers?
 
D

Dave Sexton

Hi Jake,

There is no best place. It depends on the scope and lifetime of the object.
If the object is created by a class when the class is created, and if the
object will remain useable for as long as the class that contains it, then
registering event handlers in the class's constructor is usually suitable.
If the object will be useable after the class that contains it has been
disposed then be sure to unregister the event handlers in the class's
dispose method.

If the object is created in some method rather than the class's constructor
then register the event handlers when the object is created in the method.
 
J

Jake K

Thanks. The object will only be usable in a single class. I will register
event handlers in the class' constructor. Thanks.
 
J

Jake K

Does it matter where InitializeComponent(); appears in the default
constructor? E.g. Is this correct or does InitializeComponent need to be
the first line?

namespace whatever
{

public partial class Form1 : Form
{
//fields defined here, etc.
}

public Form1 //default constructor
{
COMObject1 = new COMObjectClass();
COMObject1.MethodName += new
COMObjectLib._ICOMObjectEvents_MethosNameEventHandler(OnCOMObject1MethodName);
InitializeComponent();
}

private void OnCOMObject1MethodName()
{
}

}
 
D

Dave Sexton

Hi Jake,

In your situation it doesn't matter since COMObjectClass isn't instantiated
and configured by the designer, but you should make it a habit of putting
InitializeComponent as the first line anyway since it's not uncommon to
manipulate designer-serialized controls in the constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top