Code behind a button created with code

  • Thread starter Thread starter Notbob
  • Start date Start date
N

Notbob

Guest
I used code to create an array of buttons that show up on the screen. Now, when someone clicks on those buttons I want to know how to run the code behind it. In my program the buttons are cmdSelect(20) 20 being the array size. When they click on the 5th button I want it to say in a text box, you clicked on button 5. If someone can drive me there, I can figure out the rest of the trip. THANKS IN ADVANCE.
 
When you create the buttons, assign their Tag property their index number in the array. Also, as you create them, you need to wire up their Click events:

Visual Basic:
AddHandler btnArray(index).Click, AddressOf myEventFunction

Then you create your event handler function:
Visual Basic:
Private Sub myEventFunction(ByVal sender As System.Object, ByVal e As System.EventArgs)
    Dim btnSender As Button
    Dim intIndex As Integer

    btnSender = CType(sender, Button)
    intIndex = CType(btnSender.Tag, Integer)

    MsgBox(intIndex)
End Sub
 
Last edited:
add handler

But everytime I type that line, it underlines the addhanlder and says syntax error. I copied the exact text you orginally posted.
 
code for runtime buttons

Ok, I am not getting this at all. Maybe I need to back up and explain. In VB 6 I used to be able to take a button and draw it right onto the form. I would then copy it and paste it to the form. I was then asked to make an array of that button. In vb.net it just adds another button and calls it button2.

So found a procedure to adds the buttons through the code in an array. The problem is, when I click on those buttons nothing happens. When I stop the program to edit the code, there is no button for me to double click on to edit the code like I used to in vb6. My question is, when I click on these multiple buttons that are created at run time, what code is it accessing, and how do I edit it. I sort of understand the idea behind the addhandler thing, but it does not seem to recognize the array of buttons.
 
Maybe we should put that in a sticky thread somewhere since this same question seems to get asked in a different way every day.
 
Thanks

That was very helpful and sort of pulled it all together for me. Thanks for everyone's help. I got my button to work with your help. With this code I plan to take over the world. Thanks
 
Back
Top