Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get sender name event handler [duplicate]

Tags:

c#

eventargs

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);}
    }
like image 481
Mathias Avatar asked Nov 30 '13 05:11

Mathias


2 Answers

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);}
    }
like image 67
Vahid Nateghi Avatar answered Oct 16 '22 03:10

Vahid Nateghi


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); }
}
like image 29
Mark Hall Avatar answered Oct 16 '22 04:10

Mark Hall