Get sender name event handler [duplicate]
Asked Answered
L

2

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);}
    }
Lydie answered 30/11, 2013 at 5:16 Comment(3)
That's what the sender is, the thing that triggers the event.Schoolroom
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.Countersubject
Thanks @EvanTrimboli, didn't know if I was asking the question right.Lydie
L
19

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);}
    }
Limoges answered 30/11, 2013 at 5:37 Comment(0)
W
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); }
}
Whitelaw answered 30/11, 2013 at 5:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.