Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help on eventhandler

Status
Not open for further replies.

phinoppix

Programmer
Jul 24, 2002
437
US
I read this article about imitating VB6's control arrays on C#. What it suggested is this: Assuming I am trying to employ a single Click event on multiple buttons - b1, b2, b3 - I would instantiate a Button class (bx) and create its eventhandler. Then, I add eventhandlers to these (b1, b...) pointing to bx's.

this.b1.Click += EventHandler(bx_Click);
this.b2.Click += EventHandler(bx_Click);

It worked, but I'm stopped on one question: How do I know who's the sender? I mean how do I use the sender par to identify who's b1 or b2 or b3?

Well, I know they have their Name property, but are there better (cleaner) approach on this?

[tt]
private void bx_Click(object sender, EventArgs e)
{
Button btnHndr;
btnHndr = (Button)sender;
switch(btnHndr.Name)
{
case "b1":
MessageBox.Show("Button 1");
break;
case "b2":
MessageBox.Show("Button 2");
break;
case "b3":
MessageBox.Show("Button 3");
break;
}
}[/tt]

TIA, [peace]
 
You've pretty much got it. You could improve your current example slightly (see below), but in most cases you will find yourself using a switch block.

private void bx_Click(object sender, EventArgs e)
{
Button btnHndr;
btnHndr = (Button)sender;
MessageBox.Show(btnHndr.Text);
}
 
I suggest using the .GetHashCode() method. That will give you a unique ID for each button. Compare that to Sender.GetHashCode(). If the sender's hashcode matches a particular button... that button generated your event.

Thomas D. Greer
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top