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);}
}
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);}
}
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); }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With