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
- Private Sub raiseButton_Click()
- MessageBox.Show("Welcome to Author Code")
- End Sub
- Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
- btn.Size = New Size(150, 50)
- btn.Location = New Point(119, 30)
- GroupBox1.Controls.Add(btn)
- btn.Text = "Click me"
- AddHandler btn.Click, AddressOf ShowWelcomeMessage
- End Sub
- Private Sub ShowWelcomeMessage(ByVal sender As System.Object, ByVal e As System.EventArgs)
- MessageBox.Show("Welcome to Author Code")
- End Sub
- Private Sub ShowAnotherMessage(ByVal sender As System.Object, ByVal e As System.EventArgs)
- MessageBox.Show("Hello Guest")
- End Sub
- Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
- RemoveHandler btn.Click, AddressOf ShowWelcomeMessage
- AddHandler btn.Click, AddressOf ShowAnotherMessage
- End Sub