Get sender name event handler

Mathias picture Mathias · Nov 30, 2013 · Viewed 46.4k times · Source

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

Answer

Vahid Nateghi picture Vahid Nateghi · Nov 30, 2013

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