How to programatically fire an event

aewarnick

Senior Contributor
Joined
Jan 29, 2003
Messages
1,031
I have a couple of places in my code where it would be convenient to simulate an event. I looked on the internet but could find nothing about it.

For example, I have a date and time picker with an event - dateTimePicker_ValueChanged

How do I simulate the value changed so that everything in that block executes?
 
Can you not just call that function directly? For the "sender" pass in the variable name itself. Pass in dummy arguments for the second one.

For example:
C#:
dateTimePicker1_ValueChanged(dateTimePicker1, new System.EventArgs());

Remember, an event is just a function. The event handler code (usually in InitializeComponent) just hooks the event to call your function, but it's still just a function.

-nerseus
 
Yep, that works. I realize that I could just take everything out of the event block and put it in a regular method (C# function) but I really wanted to know how to do that anyway.

Thanks.
 
No such thing as "RaiseEvent" in C# ??

In VB (yes, I read your signature, but VB is my home turf) In VB you need to declare an Event

e.g
Code:
Public Event NothingHappened (sender as Object, e as NothingHappenedEventArgs(
[\code]

and then

[code]
RaiseEvent NothingHappened (me, New NothingHappenedEventArgs (arg1, arg2))
[\code]

(You could use EventArgs as the class for your arguments but I recommend always to derive your own special EventArgs class, this will reduce correction times drastically later in the project. Believe me :) )
 
Events are probably the biggest difference between C# and VB. With VB, you use its helper functions to add and remove delegates, and even to call the list of delegates. In C# you have direct access to the event and you add and remove delegates yourself, and just call the delegate list like any other function.
 
I hope my signature does not offend anyone. If it does I will most certainly change it. Just let me know.
 
Back
Top