Newbie: event handlers with dynamically created controls

C

Christy Davids

I'm working on an application that dynamically generates
buttons based on directory names in a file system. Click
a button (directory) and the form refreshes with more
buttons (subdirectories). I can generate the controls
just fine, but I'm having trouble with attaching the event
handlers to them.

I understand the syntax of...

AddHandler MyButton.Click, AddressOf MyButton_Click

....but I need an arbitrary number of different handlers,
one for each button. I'm still pretty weak in my OOP but
I imagine I should be writing the handler as a class that
is instantiated for each button. I just can't quite
figure out how to do this.

Can some kind soul help me out here? :)

Christy

Here's what I've got for loading the buttons right now:

Private Sub LoadButtons(ByVal path As String)
Dim dir As String
Dim text As String
Dim i As Integer
Dim letter As Char
Dim start As Integer

For Each dir In Directory.GetDirectories(path)
Dim NewButton As New Button
NewButton.Size = New System.Drawing.Size(220,
15)
NewButton.Left = 10
NewButton.Top = 18 * ButtonCounter + 5
For i = 0 To dir.Length - 1
If dir.Chars(i) = "\" Then
start = i + 1
End If
Next
text = dir.Remove(0, start)
NewButton.Text = text
Me.Controls.Add(NewButton)
ButtonCounter += 1

'Attach an event handler to the click event
HERE'S WHERE MY PROBLEM IS!

'Store the button in a collection
DynamicButtons.Add(NewButton)
Next
End Sub
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi Christy,

In fact, you will need only one handler procedure for all the buttons. But,
this handler should be able to recognize "whose" event it is currently
handling, and this can be determined by analysing the Sender argument.

You will just be applying the equality operator to the Sender value and each
of the buttons stored in the DynamicButtons collection. Now that the button
that has been clicked is determined, the rest should be simple.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top