Search This Blog

Wednesday, November 28, 2012

Handle events for dynamic run-time controls - VB.NET

VB.NET > Statements > AddHandler > Add event to dynamic control

Use AddHandler and AddressOf to add event to dynamic control

Example

Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Data
Imports System.Text
Imports System.Windows.Forms
Imports System.Drawing.Drawing2D
Imports System

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  Dim btn = New Button() //add dynamic control to form
  btn.Text = "Click here"
  btn.Size = New System.Drawing.Size(100, 100)
  btn.Location = New System.Drawing.Point(50, 50)
  AddHandler btn.Click, AddressOf Button1_Click  //add event to control
  Me.Controls.Add(btn)
End Sub

Protected Sub Button1_Click(sender As System.Object, e As System.EventArgs)
  Dim btn As Button = sender
  MsgBox(btn.Text)
End Sub

End Class