Events
An Event is a message sent by an object that indicates the occurrence of an action. The Action could be done by user interaction, such as button click or property change and so on.
The object that raises the event is called event sender. Event sender does not know which method or object is going to receive the event when it raises.
The Event is declared by using the "Event" keyword.
- public class PrintKOT: AbstracTransaction
- {
-
- public event SaveDetailsHandler PrintHandlerEvent;
-
-
- public PrintKOT(TransactionProperties trnprt, ApiParameters parameters)
- {
- param = parameters;
- trn = trnprt;
- suport = new Transactions.Support(parameters);
- }
Delegates
A Delegate is a type that holds the reference of the method. Delegate is declared with a signature that shows return type and the parameters. Delegate acts like an intermediary between event code and the code that handles the event. If you want to pass specific parameters through the event, then you can use the delegate.
Delegate is declared by the "delegate" keyword.
- public class SaveDetailArgs : EventArgs
- {
- public List<ItemProperty> ItemList { get; set; }
- public bool isReprint { get; set; }
- }
-
- public delegate void SaveDetailsHandler(object sender, SaveDetailArgs args);
The EventArgs class is the base class for all the event data classes. EventArgs is also the class you can use when your event does not have any data associated with it. When you create an event that is only meant to notify other classes that something happened and does not need to pass any data.
How to call an Event
- First, we need to check whether the event is raised or not.
- If event is not null, then pass your parameter if needed.
- Here, PrintHandlerEvent doesn't know which method is going to receive this.
- public override bool btnClick(ReportTotalSummary reportsSum)
- {
- if (trn.saveDetailItemDetailsList.Count > 0)
- {
-
- if (PrintHandlerEvent != null)
- {
- SaveDetailArgs args = new SaveDetailArgs() { ItemList = lst, isReprint = false };
- PrintHandlerEvent.Invoke(null, args);
-
- }
-
- }
- return true;
- }
After invoking the event, we need to define event handlers.
Event Handler
To respond to the event, we need to define the event handler method in the event receiver class. This event handler should match with delegate signature.
In event handler, you are going to perform the action. In my example, I need to print the report.
- PrintKot kot = new PrintKot();
- kot.PrintHandlerEvent += TransactionWindow_PrintHandlerEvent;
-
- private void TransactionWindow_PrintHandlerEvent(object sender, SaveDetailArgs args)
- {
- if (args.isReprint)
- {
- RePrintKOT_Report();
- }
- else
- {
- NewKOTPrint(args.ItemList);
- }
- }