Public Group

help with object sender (C#)

This topic is 5058 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

okay, so i got lots of buttons on the screen, and i want them all to call the same function when any one of them is clicked... that's easy...

this.button1.Click += new System.EventHandler(this.button1_Click);
this.button2.Click += new System.EventHandler(this.button1_Click);
this.button3.Click += new System.EventHandler(this.button1_Click);


anyhoo, inside of button1_Click() i want to be able to do something to the button that I just clicked... i'm sure this is done with the sender object, but i can't figure it out... this is what I actually have:

Button[,] btnBoard = new Button[3,3];

// ...

for(int x = 0; x < 3; x++)
{
for(int y = 0; y < 3; y++)
{
// ...

// NOTE
this.btnBoard[x,y].Click += new System.EventHandler(this.btnHandler(x, y));
}
}

//...

public void btnHandler(int x, int y)
{
MessageBox.Show("Button[" + x + "," + y + "] has been clicked...");
}


so here's the problem... "NOTE 1" is giving me an error message... it won't let me do that... it'll only let me call a OnClick function from another button... but that way i can't figure out what button is calling the function... HELP! I can try and be more clear if you're counfused... heh... anyhoo, thanks for your time...

yar... anyone?

Share on other sites
1) The prototype of the event handler must match the Click delegate (object, EventArgs)

2) Yes, the sender object is the guy who was clicked. You could just do a search through the array if you need to find it in there, or you could just cast it to the type:
Button b = (Button)sender;

Share on other sites
For that to work that way, btnHandler(x, y) has to return a delegate... but I don't think C# lets you do something like that. Don't event handlers get the object that called them as their first argument anyway?

Like this, I mean:
public delegate void EventHandler(object sender, EventArgs e);

1. 1
2. 2
3. 3
4. 4
Rutin
17
5. 5

• 11
• 34
• 12
• 12
• 11
• Forum Statistics

• Total Topics
631412
• Total Posts
2999939
×