Question Avoiding 200 Button_Click Subs

kylegee

Member
Joined
Sep 9, 2008
Messages
10
Programming Experience
Beginner
So basically I have 200 little buttons on a form. When one is clicked I'm want its name added to a DataGridView Cell. Obviously I can make a Button_Click Sub for each button and transfer the data that way, but there must be a more efficient way.

Thanks in advance,

Kyle
 
How are the buttons put on the form? Are they done in the designer or do you do it in code in the form's load event or some other event?
 
One way to do it is to highlight all of the buttons and double click one of them, this will switch it to the code view with all of them having their click event subs already created. Now all you gotta do is code each one or move the handles clauses all up to one (delete the other subs) and use the Sender object to know which button was clicked when that routine runs.

Another way to do this is to loop through all of the controls in the panel looking for buttons and use the AddHandler to assign the click events of the buttons to a sub routine and again use the sender object to know which button was clicked when the routine runs. Also keep in mind that you should use the RemoveHandler when the form closes or the panel's destroyed to help with resource management.
 
One way to do it is to highlight all of the buttons and double click one of them, this will switch it to the code view with all of them having their click event subs already created.

Long way round! If you highlight all the buttons, then go to Properties, lightning bolt (events), Click and then jsut type a name in there and press return.. the IDE should link them all to that one handler name for you ;)


I would ask why there are 200 buttons on a form, but over time, I've come to know that it can be a real can of worms..
 
Thanks for your help.

This was put into the Control Click sub:


VB.NET:
        Dim clickedCtrl As Control

        clickedCtrl = DirectCast(sender, Control)

clickedCtrl.Name returns the name of the button!
 
Back
Top