Using AddHandler and AddressOf

106 26


Adding Run-Time Event Handlers Dynamically

"Erick" had a problem figuring out how to record the sequence of clicks in a program. The program displayed a matix of CheckBox controls but the key information that was needed was the sequence that they were checked.

Piece of cake, right? Just add an event subroutine that handles the Click event for all of the Checkboxes and capture the sequence.

Private Sub SequenceCapture( _ ByVal sender As Object, - ByVal e As System.EventArgS) _ Handles CheckBox01.CheckChanged, _ Checkbox02.CheckChanged, _

...


and so forth followed by ...

CheckBoxSequence(CheckSeq) = sender.name CheckSeq += 1

Not so fast there, sailor. There's more to the problem.

The matrix of CheckBox controls is variable. The number of rows and columns is entered into textboxes and the CheckBox matrix is created in a double loop:

For RowCount = 1 To RowSizeFor ColCount = 1 To ColSizeDim ChkBox As New CheckBoxChkBox.Name = "Checkbox" & i.ToString + 1ChkBox.Location = _ New Point(20 * ColCount, 20 * RowCount)ChkBox.Size = New Size(20, 20)Me.Controls.Add(ChkBox)i += 1NextNext

Adding handlers, a "compile-time" solution, doesn't work now. For one thing, you don't even know how many CheckBox controls there will be at run-time. We need a run-time solution instead.

The AddHandler statement fills the bill just fine. Use AddressOf to point to the right subroutine to handle the CheckedChanged event for each CheckBox component.

Dim ChkBox As New CheckBoxAddHandler ChkBox.CheckedChanged, AddressOf SequenceCapture

Here's the source for a complete example program:


Public Class Form1 Dim CheckBoxSequence() As String Dim CheckSeq As Integer = 0 Private Sub Form1_Load( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Dim CheckBoxMatrix() As String Dim MatrixSize, i, RowCount, ColCount As Integer Dim RSize, CSize As Integer RSize = CInt(RowSize.Text) CSize = CInt(ColSize.Text) MatrixSize = RSize * CSize ReDim CheckBoxMatrix(MatrixSize - 1) ReDim CheckBoxSequence(MatrixSize - 1) i = 0 For RowCount = 1 To RSizeFor ColCount = 1 To CSize CheckBoxMatrix(i) = i.ToString Dim ChkBox As New CheckBox AddHandler ChkBox.CheckedChanged, _AddressOf SequenceCapture ChkBox.Name = "Checkbox" & i.ToString + 1 ChkBox.Location = _New Point(20 * ColCount, 20 * RowCount) ChkBox.Text = "" ChkBox.Size = New Size(20, 20) Me.Controls.Add(ChkBox) i += 1Next Next End Sub Private Sub SequenceCapture( _ ByVal sender As Object, _ ByVal e As System.EventArgs) CheckBoxSequence(CheckSeq) = sender.name CheckSeq += 1 End Sub Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click For i As Int16 = 0 To CheckSeqLabel1.Text = _ Label1.Text & CheckBoxSequence(i) & vbCrLf Next End SubEnd Class
Source...

Leave A Reply

Your email address will not be published.