Reputation: 503
I have a large number of buttons on a form (144 buttons). The names of each button is a combination of different factors.
I need them to all do the same thing when pressed. I have this event under a Private Sub called "ClickButton".
I want to use a loop, to AddHandler each button to the "ClickButton" event.
First however, I need to address each button. I do this by constructing their name dynamically in a loop.
Dim PeriodRoomID As New Button
Dim cntrl() As Control
For Each Row In dsAllRooms.Tables("sqlAllRooms").Rows
For Count = 1 To 13
RoomID = Row.Item(0)
'This is where the name of each room is dynamically created.
'It is stored in PeriodRoomID.name
PeriodRoomID.Name = "R02" & RoomID.PadLeft(3, "0"c) & Count
cntrl = Me.Controls.Find(PeriodRoomID.Name, True)
AddHandler cntrl(0).Click, AddressOf ClickButton
Next
Next
The problem is nothing happens. The AddHandler doesn't work. However, if I simply write one of the names of the buttons;
AddHandler R020011, AddressOf ClickButton
Then it does work. Something is going wrong at Me.Controls.Find. It doesn't seem to be able to find any button under that name which is strange because I use the same code in other sections and it finds the button.
Upvotes: 1
Views: 1438
Reputation: 4348
You define Dim PeriodRoomID As New Button
out of for
statement so each time you set name
you set it to the same button PeriodRoomID
so you don't need this button and cntrl
neither at all just :
For Each Row In dsAllRooms.Tables("sqlAllRooms").Rows
For Count = 1 To 13
RoomID = Row.Item(0)
'This is where the name of each room is dynamically created.
dim Ctrls = Me.Controls.Find("R02" & RoomID.PadLeft(3, "0"c) & CStr(Count), True)
If (Ctrls.Count > 0) Then
AddHandler Ctrls(0).Click, AddressOf ClickButton
End If
Next
Next
Upvotes: 1