AddHandler problem

Reno

Member
Joined
Apr 9, 2009
Messages
8
Programming Experience
1-3
Hey Guys thanks for taking the time to read this. I am creating a program and at one point it requires the user to create labels etc then it saves there positions to a file. It then reloads them at start-up. This all works perfectly.

I am storing my labels in a array of 50. That also works fine, however my problem arises when I want to an a handle to it. I want to add a when clicked event. However when i try the code:

VB.NET:
Me.Controls.Add(Label(I))
AddHandler Label(I).Click, AddressOf Label(I)_Click

It doesn't like me using brackets in the AddressOf. If anyone can help out i will be very greatful.

:)
 
AddressOf Label(I)_Click
No, it doesn't like that, you can name the method anything as long as it's a valid method name, "DynamicLabels_Click" for example.
 
You have to have written the event handler already, so you have to have already given it a name. You just specify that name. You will only have one method and it will handle the event for all Labels. Inside the event handler you use the 'sender' parameter to get a reference to the Label that raised the event.
 
Hmmm I still don't seem to have it working, this is what I have got:

VB.NET:
Private Sub Computer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Computers(I).Click
  
Some Code

End Sub

And I create the event handler here:

VB.NET:
AddHandler Computers(I).Click, AddressOf Computer_Click

It doesn't like the "Handles Computer(I).Click"

I am sure it is something simple.

Thanks for the replies!
 
Last edited:
You don't need the "Handles Computer(I).Click" at all. Putting that at the end of the method turns the method into an event handler, but you are manually assigning an event handler with your other code. Just remove "Handles Computer(I).Click" and it should work fine.
 
Your event sub will look similar to this:
VB.NET:
Private Sub Computer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
  
  'Use 'sender' to know what label you're handling

End Sub
And your AddHandler will look similar to this:
VB.NET:
For i As Integer = 0I To 49I
  AddHandler Computers(i).Click, AddressOf Computer_Click
Next i
 
JB, what is the "I" in "0I To 49I"? I don't think I've ever seen that in a For Loop.


*Edit* By playing around with it; I discovered that it specifies that the number is an Integer. But is that ever actually necessary?
 
Last edited:
JB, what is the "I" in "0I To 49I"? I don't think I've ever seen that in a For Loop.
It's a compiler declarative, it means I'm telling the compiler that the integer is indeed an integer when the code gets compiled instead of the compile guessing that it's an integer when compiling.

S = Short
I = Integer
L = Long
D = Decimal
F and ! = Single (1.0! and 1.0F both mean you're specifying a single)
R = Double
 
Back
Top