8

I hope the name gives justice to my question... So, I just started making a memory game, and there are 25 checkbox buttons which I am using to show the items.

I was wondering whether there was a way to tell from either the EventArgs or the Object what button it was sent from if each button used the same event handler.

private void checkBox_CheckedChanged(object sender, EventArgs e)
    {
        checkBox = Code which will determine what checkBox sent it.
        if (checkBox.Checked)
        { Box.ChangeState(checkBox, true); }
        else { Box.ChangeState(checkBox, false);}
    }
deathismyfriend
  • 2,182
  • 2
  • 18
  • 25
Mathias
  • 213
  • 2
  • 4
  • 7
  • That's what the `sender` is, the thing that triggers the event. – Evan Trimboli Nov 30 '13 at 05:19
  • I'm not sure if it's possible, but if you create your own subclass of `EventArgs` and pass it as a parameter instead, you could define the name of the method in there. But so far I haven't found a way to overwrite the standard signature. – Jeroen Vannevel Nov 30 '13 at 05:24
  • Thanks @EvanTrimboli, didn't know if I was asking the question right. – Mathias Nov 30 '13 at 06:07

2 Answers2

18

Try setting the Name attribute of each checkbox when defining them and then using ((CheckBox)sender).Name to identify each individual checkbox.

Definition time:

CheckBox chbx1 = new CheckBox();
chbx1.Name = "chbx1";
chbx1.CheckedChanged += checkBox_CheckedChanged;
CheckBox chbx2 = new CheckBox();
chbx2.Name = "chbx2";
chbx2.CheckedChanged += checkBox_CheckedChanged;
CheckBox chbx3 = new CheckBox();
chbx3.Name = "chbx2";
chbx3.CheckedChanged += checkBox_CheckedChanged;

And

private void checkBox_CheckedChanged(object sender, EventArgs e)
    {
        string chbxName = ((CheckBox)sender).Name;
        //Necessary code for identifying the CheckBox and following processes ...
        checkBox = Code which will determine what checkBox sent it.
        if (checkBox.Checked)
        { Box.ChangeState(checkBox, true); }
        else { Box.ChangeState(checkBox, false);}
    }
Vahid Nateghi
  • 576
  • 5
  • 14
5

The sender object is actually the Control that initiated the event, you can cast it to the proper type to access all of its properties. You can use the Name as stated or as I sometimes do is to use the Tag Property. But in this case just casting sender to a CheckBox should work.

private void checkBox_CheckedChanged(object sender, EventArgs e)
{
    CheckBox cb = (CheckBox)sender;
    if (cb.Checked)
    { Box.ChangeState(cb, true); }
    else { Box.ChangeState(cb, false); }
}
Mark Hall
  • 53,938
  • 9
  • 94
  • 111