Reputation: 5126
How could I execute an event, without it actually happening?
For example, how would I execute a button1_Click()
event in code, without clicking the button?
The problem is that I have a WebClient
, which doewnloads lists of files.
Each time it finishes downloading a file it executes a DownloadFileCompleted
event, which then downloads the next file.
However, some files aren't downloaded (all in plan), so the event is not executed. How could I execute it? Thanks
Upvotes: 0
Views: 108
Reputation: 14432
If the Name of your Button is button1, you can raise the click-event by following line of code:
button1.PerformClick();
Hope this helps!
Edit:
Or like others have said, put your logic in a separate method and call the method when needed.
Upvotes: 0
Reputation: 13285
You should move the code out of your event handler and into a function.
You can then call this function from the both the event and any other method you need to trigger it.
So instead of:
private void button1_Click()
{
//do something
}
You have:
private void button1_Click()
{
doSomething();
}
public void doSomething()
{
//do something
}
Upvotes: 0
Reputation: 6357
Controls often have the ability to raise an event e.g. Button.PerformClick in your case
Upvotes: 1
Reputation: 62265
Just insert all code present in the event handler in a separate function, like
private void button1_click(...)
{
func(...)
}
public void func(...)
{
//even handler code
}
and if you don't what to raise an event, or can't, just call
func(...)
I personally against calling event handler esplicitly, but prefer this approach. To me seems more clear code structure.
Upvotes: 7
Reputation: 5555
button1_Click() is just a method, so you can execute it even if you bound it to an event.
Upvotes: 0
Reputation: 482
You could just feed it empty values and call it like a normal function (after all, it is a normal function that simply needs a sender and the appropriate event arguments). E.g.
button_click(new object(), new System.EventArgs());
Those are the normal events for a standard GUI button, your button might need different events. This approach works, if you only need your button to detect the click and don't want to use the event arguments.
Upvotes: 1