Tuesday, June 4, 2024

How to create event for user control - What is delegate - how to create automatic method from event

For me it is like a function that is having no body.

Delegate is used for callbacks of methods. It is just like a function but not having body. 

Delegate is used  to pass a method as a parameter .


 public delegate void SignatureHandler(object sender, EventArgs e);

        public event SignatureHandler SignatureEvent;

        public delegate void SignatureJSHandler(object sender, EventArgs e);

        public event SignatureJSHandler SignatureJSEvent;

        public delegate void SendConfirmationHandler(object sender, EventArgs e);

        public event SendConfirmationHandler SendConfirmationEvent;


<uc1:DigitalSignatureButton runat="server" ID="DigitalSignatureButton" OnSignatureEvent="buttonSave_OnClick" OnSignatureJSEvent="buttonSaveJS_OnClick" />


1>create delegate without parameters(Create delegate in separate class)

public delegate void MyDel();

2>Then create a function like this delegate that is having no parameters.

 public void MyFunction()

    { }

3>Then create instance of delegate for calling the function and delgate

 MyDel a = new MyDel(MyFunction);

 a+= MyFunction;

 MyFunction();

or 3rd step you can do by changing thins

MyDel asp = new MyDel(MyFunction);

asp.Invoke();

=============************===============

1>create delegate with parameters(Create delegate in separate class)

public delegate void MyDel(int a);

2>Then create a function like this delegate that is having  parameters.

 public void MyFunction(int a)

    { }

3>Then create instance of delegate for calling the function and delgate

 MyDel a = new MyDel(MyFunction);

 a+= MyFunction;

 MyFunction(5);

or 3rd step you can do by invoke method

 MyDel asp = new MyDel(MyFunction);

 asp.Invoke(5);  //in brackets parameter


There is one other way to call delegate or you can say it is an event

public delegate void MyDel();

 public event MyDel MyTestEvent;

 MyTestEvent+=Login_MyTestDel; // Automatic crate method by using += with event

        MyTestEvent.Invoke();

private void Login_MyTestDel()

    {}


No comments:

Post a Comment