Reputation: 476
I found some similar questions but none of them on C#
Winforms
. I have many similar methods for different Checkboxes
I have on my form, but now the number of checks is about to double and I'm looking for a simpler way of doing this.
Here's an example:
private void CheckPET_Click(object sender, EventArgs e)
{
if (CheckPET.Checked)
{
CheckAdicionarMaterial("PET");
}
else
{
if (Confirmacao())
CheckRemoverMaterial("PET");
else
CheckPET.Checked = true;
}
}
I have one of these for each Checkbox
, and all of them follow the same pattern, so if I could have a method that handles all clicks I could do something like this:
private void GenericCheckbox_Click(object sender, EventArgs e)
{
if (Checkbox.Checked)
{
CheckAdicionarMaterial(Checkbox.Text);//The text of the boxes is always the string I want to pass here.
}
else
{
if (Confirmacao())
CheckRemoverMaterial(Checkbox.Text);
else
Checkbox.Checked = true;
}
}
What can I do to achieve this?
Upvotes: 1
Views: 786
Reputation: 89
If I understand the question correctly - binding a single function as an event handler for several checkboxes?
private void checkBox_CheckedChanged(object sender, EventArgs e)
{
CheckBox checkbox = sender as CheckBox;
if (checkbox == null) return;
if (checkbox.Checked)
{
CheckAdicionarMaterial(checkbox.Text);//The text of the boxes is always the string I want to pass here.
}else
{
if (Confirmacao("Desmarcar removerá todas ocorrências do material. Continuar?"))
CheckRemoverMaterial(checkbox.Text);
else
checkbox.Checked = true;
}
}
Upvotes: 2