Dynamic controls and handlers

  • Thread starter Thread starter David D Webb
  • Start date Start date
D

David D Webb

I have a form with a number of buttons that are generated in a panel based
on the results of a query. They all use the same click event handler. I am
having trouble determining which button was pressed. I can only go by the
button text or the button position to distinguish them - neither of which
works well for my situation. Is there a better way? Should I create my own
button class inheiriting Button and add my own custom id fields?

Thanks/Dave

They are created as:

while (...)
{
Button btnClient = new Button();
btnClient.Location = new System.Drawing.Point(8, (numClients*32) + 8);
btnClient.Width = 150;
btnClient.Text = full_name;
btnClient.Click += new System.EventHandler(btnClient_Click);
pnlScroll.Controls.Add(btnClient);
numClients ++;
}

I have a generic handler for these buttons:

private void btnClient_Click(object sender, System.EventArgs e)
{
Button btnClient = (Button)sender;
// Determine which button was pressed here

}
 
There are a number of options, here are a few:-

You could add references to your buttons to a hashtable with a unique value
to identify them, and then do a lookup on this from the sender argument of
your event handler.

You could use Chris's code sample for determining the control name at
runtime:-
http://blog.opennetcf.org/ctacke/PermaLink,guid,64c28b10-d3a8-4c6b-b11a-2ae2de4bdaf1.aspx

Finally you could derive your own control from Button and add a Name, Tag or
similar property which you can use to uniquely identify each one. However
there will be a bit of extra work required to create designer support for
the control.

Peter

--
Peter Foot
Windows Embedded MVP
www.inthehand.com | www.opennetcf.org

Do have an opinion on the effectiveness of Microsoft Windows Mobile and
Embedded newsgroups? Let us know!
https://www.windowsembeddedeval.com/community/newsgroups
 
Thanks Peter,

Since they were dynamic controls, I didn't need designer support, so the
third solution turned out to be extremely easy. Love this .NET stuff...

-Dave
 
Back
Top