Can I call an event in code?

D

Dom

In the days of VB, it was possible to do the following: "Call
Button1_Click()", although there was some argument about whether this
was asking for trouble.

Is it possible to do it in CSharp? The trouble that I see is that
every event handler needs arguments. But can you do something like
"Raise Button1_Click"?

Dom
 
Z

zacks

In the days of VB, it was possible to do the following: "Call
Button1_Click()", although there was some argument about whether this
was asking for trouble.

Is it possible to do it in CSharp? The trouble that I see is that
every event handler needs arguments. But can you do something like
"Raise Button1_Click"?

Dom

ControlName.PerformClick()
 
N

Nicholas Paldino [.NET/C# MVP]

Dom,

An event handler is nothing more than a method. That method is called
through a delegate by the source of an event. However, there is nothing
that is preventing you from calling that method. To that end, you have to
supply the method with what it expects, in this case, the source of the
event (sender) and the EventArgs instance (or class derived from it).

Now, depending on the code in the event handler, you could possibly get
away with not providing values for those parameters (null for sender, and
default values for whatever is passed as the second parameter).

However, if you are trying to synthesize the firing of the event, then
you really should look for a method on the object itself which will fire the
event.

If you are just trying to share logic between calls, then you should
have another method which takes the parameters you need, and then just call
it from the event handler, passing the appropriate information, and the
other section of your code, again, passing the appropriate information.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

Dom said:
In the days of VB, it was possible to do the following: "Call
Button1_Click()", although there was some argument about whether this
was asking for trouble.

Is it possible to do it in CSharp? The trouble that I see is that
every event handler needs arguments. But can you do something like
"Raise Button1_Click"?

Of course you can, the event handler is just a regular method, you can call
it from code if you want.

Regarding the parameters, depending of the use you give them you can pass
null.
 

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

Top