help with object sender (C#)

Started by
2 comments, last by twix 19 years, 8 months ago
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...
---Current project - Duck Hunt 2: Free at Last!http://www.duckhunt2.cjb.net
Advertisement
yar... anyone?
---Current project - Duck Hunt 2: Free at Last!http://www.duckhunt2.cjb.net
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;

In time the project grows, the ignorance of its devs it shows, with many a convoluted function, it plunges into deep compunction, the price of failure is high, Washu's mirth is nigh.

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);

I'm so slow. [sad]

This topic is closed to new replies.

Advertisement