Quantcast
Channel: AuthorCode » Windows Controls
Viewing all articles
Browse latest Browse all 10

Add And Remove Action Handler Dynamically

$
0
0

In this article we will learn how to create a control with event handlers at run time using vb.net programming language. we will also learn from here that how we can remove event handler or stop handling event during program execution.

we use the AddHandler and RemoveHandler statements for doing this, Both statements takes two arguments, first is the name of an event from an event sender such as a control, and second is an expression that evaluates to a delegate.

When you use associates an event handler with an event raised by an object using Addhandler like this:

AddHandler ctrl.xEvent, AddressOf ctrlEventHandler

and you can use RemoveHandler, which disconnects an event from an event handler like this:

RemoveHandler ctrl.XEvent, AddressOf ctrlEventHandler

Example

Dim btn As New Button
  1. Private Sub raiseButton_Click()
  2.         MessageBox.Show("Welcome to Author Code")
  3. End Sub
  4.  
  5. Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
  6.         btn.Size = New Size(150, 50)
  7.         btn.Location = New Point(119, 30)
  8.         GroupBox1.Controls.Add(btn)
  9.         btn.Text = "Click me"
  10.         AddHandler btn.Click, AddressOf ShowWelcomeMessage
  11. End Sub
  12.  
  13. Private Sub ShowWelcomeMessage(ByVal sender As System.Object, ByVal e As System.EventArgs)
  14.         MessageBox.Show("Welcome to Author Code")
  15. End Sub
  16. Private Sub ShowAnotherMessage(ByVal sender As System.Object, ByVal e As System.EventArgs)
  17.         MessageBox.Show("Hello Guest")
  18. End Sub
  19.  
  20. Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
  21.         RemoveHandler btn.Click, AddressOf ShowWelcomeMessage
  22.         AddHandler btn.Click, AddressOf ShowAnotherMessage
  23. End Sub

Viewing all articles
Browse latest Browse all 10

Trending Articles