问题
I have 10 check boxes in a group box. The top check box labeled "All" checks the other 9 check boxes when checked is true for "All"
In the other 9 checkboxes, I have essentially the same code. Here is a sample for two of the check boxes:
private void ckDal_Click(object sender, EventArgs e)
{
if (ckDal.Checked == false)
ckAll.Checked = false;
}
private void ckHou_Click(object sender, EventArgs e)
{
if (ckHou.Checked == false)
ckAll.Checked = false;
}
I hate repeating the same code. How would I create a delegate to accomplish the above with just one event method?
回答1:
You can use single Click event handler for all CheckBoxes. Actual CheckBox, which raised the event, will be available from sender parameter. Just cast it to CheckBox type:
private void ck_Click(object sender, EventArgs e)
{
if (!((CheckBox)sender).Checked)
ckAll.Checked = false;
}
Also you don't need to compare boolean values with true/false - you can use them directly in if statement.
BTW you should also verify case when all CheckBoxes were checked, and set ckAll.Checked = true in that case.
回答2:
private void CheckBoxClick(object sender, EventArgs e)
{
if (!((CheckBox)sender).Checked)
ckAll.Checked = false;
}
来源:https://stackoverflow.com/questions/14031490/delegate-to-replace-repeating-code