Add and remove event handlers dynamically in .NET

.NET lets you add and remove Event Handlers dynamically on the fly. Your code can start and stop handling events at any time during program execution. Also, you can tie the same code (event handler) to multiple events similar to the Handles clause in VB.NET.

The VB.NET AddHandler and RemoveHandler statements allow this behavior. Both statements take two arguments: the name of the event to handle and the name of the procedure that will handle the event.

Dynamically add and remove an event handler in VB.NET:

    Public Class MyClass
        '
        ' Declare the event to be raised.
        '
        Public Event MyEvent

        Sub RaiseMyEvent()
            '
            ' Method to raise the event.
            '
            RaiseEvent MyEvent 
        End Sub
    End Class

    Public Class Test
      Sub TestEvent()
          '
          ' Create the object that raises the event you want to handle.
          '
          Dim myobj As New MyClass()
          '
          ' Associate the code to be executed (event handler) with the event.
          '
          AddHandler myobj.myEvent, AddressOf MyEventHandler
          '
          ' Tell the object to raise the event. It will be handled by sub MyEventHandler.
          '
          myObj.RaiseMyEvent()
          '
          ' Dis-associate the handler from the event.
          '
          RemoveHandler myobj.myEvent, AddressOf MyEventHandler
          '
          ' Tell the object to raise the event. It will NOT be handled by sub MyEventHandler.
          '
          myObj.RaiseEvent()
     End Sub

      Sub MyEventHandler()
          '
          ' Code to be executed when the event is raised.
          '
          MsgBox("I caught the event!") 
      End Sub
    End Class

C# lets you to do the same using delegates which is what VB uses behind the scenes. To learn more about delegates and how to define event arguments click here.

    namespace MyClass
    {
        public delegate void MyEventHandler(EventArgs e);

        public class MyClass
        {
            // Declare the event to be raised.
            public event MyEventHandler MyEvent;
 
            public void RaiseMyEvent()
            {
                // Method to raise the event.
                MyEvent(EventArgs.Empty);
            }
        } //MyClass
    } //namespace

    public class Test
        public void TestEvent()
        {
            //
            // Create the object that raises the event you want to handle.
            //
            MyClass myobj = new MyClass();
            //
            // Associate the handler with the event.
            //
            myobj.MyEvent += new MyEventHandler(MyHandler);
            //
            // Tell the object to raise the event. It will be handled by sub MyHandler.
            //
            myObj.RaiseMyEvent()
            //
            // Dis-associate the handler from the event.
            //
            myobj.MyEvent -= new MyEventHandler(MyHandler);
       }

        public void MyHandler()
        {
            // Code to be executed when the event is raised.
            MessageBox.Show("I caught the event!");
        }
    }

You can associate the same handler to multiple events in VB.NET:

    AddHandler Textbox1.KeyPress, AddressOf NumericValuesOnly
    AddHandler Textbox2.KeyPress, AddressOf NumericValuesOnly
    . . . 
    AddHandler TextboxN.KeyPress, AddressOf NumericValuesOnly

    Sub NumericValuesOnly(_
                ByVal sender As System.Object, _
                ByVal e As System.Windows.Forms.KeyPressEventArgs)
        
        Select Case Asc(e.KeyChar)
            Case AscW(ControlChars.Cr) 'Enter key
                e.Handled = True

            Case AscW(ControlChars.Back) 'Backspace

            Case 45, 46, 48 To 57 'Negative sign, Decimal and Numbers

            Case Else ' Everything else
                e.Handled = True
        End Select
    End Sub

C# also lets you add and remove event handlers dynamically:

    Textbox1.KeyPress += new System.EventHandler(NumericValuesOnly);
    Textbox2.KeyPress += new System.EventHandler(NumericValuesOnly);
    . . . 
    TextboxN.KeyPress += new System.EventHandler(NumericValuesOnly);

    private void NumericValuesOnly(object sender, 
                System.Windows.Forms.KeyPressEventArgs e )
    {
        . . .     
    }

    //
    // Remove handlers from the KeyPress events.
    //
    Textbox1.KeyPress -= new System.EventHandler(NumericValuesOnly);
    Textbox2.KeyPress -= new System.EventHandler(NumericValuesOnly);
    TextboxN.KeyPress -= new System.EventHandler(NumericValuesOnly);



About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2024 TheScarms
Goto top of page