problem,adding new control

alaa gomaa

Member
Joined
Apr 16, 2007
Messages
13
Programming Experience
1-3
I need help , when user add new button for example ,
how i can make click event to this button when program are using.
:mad:
 
VB.NET:
Private Sub clickEvent(Byval sender as Object, Byval e as Eventargs)
   MessageBox.show(Directcast(sender, button).Name)
End Sub

Dim nButton as New button
nButton.Name = "button1"
nButton.Text = "Button"
{the rest of the properties}
AddHandler nButton.Click, AddressOff clickEvent
Me.Controls.add(nButton)

This is not tested code as i have not the VS here with me. But mainly you need add/removehandler to add or remove the event.

Regards :)
 
If you always have a single instance of that button at a time, you could declare it like this

VB.NET:
private withevents btn_MyButton as Button

and then declare event handlers as such

VB.NET:
private sub btn_Mybutton_Click(sender as Object, args as eventArgs) [B]handles[/B] btn_MyButton.Click

The trick is to use the "withevents" keyword to make your instance variable appear in the code editor's upper combobox (like those you create in the designer). That way you can use the variable in your handles clauses. All you need to do then is to assign the button you are creating to this variable and the event handlers will be created and disposed of as needed.

PS. Be careful if you use the AddHandler clause as the delegate that is created will possess a reference to your object and you must use the RemoveHandler clause before the object can be garbage collected. If an object is disposed without being cleared of its event handlers, you will be facing a memory leak.
 
Back
Top