Sign in to follow this  
pimple

help with object sender (C#)

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...

Share this post


Link to post
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 this post


Link to post
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);

I'm so slow. [sad]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this