FROM#
I have 3 checkboxes on each line of 8 lines. I want the third checkbox on each line to be checked only when the first two checkboxes are unchecked. I don't want to write a checkRow () method for every row.
What's the best way to do this?
private void checkRow()
{
for (int i = 0; i < 8; i++)
{
var arraylist = new[] { checkbox1, checkbox2, checkbox3 };
if (checkbox1.Checked || checkbox2.Checked)
{
arraylist[2].Checked = false;
}
else
arraylist[2].Checked = true;
}
}
private void checbox1_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
private void checbox2_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
private void checbox3_CheckedChanged(object sender, EventArgs e)
{
checkRow();
}
In reply.
private void checkRow()
{
var arraylist = new[] { checkEdit1, checkEdit2, checkEdit3 };
var arraylist1 = new[] { checkEdit4, checkEdit5, checkEdit6 };
var arraylist2 = new[] { checkEdit7, checkEdit8, checkEdit9 };
var array = new[] { arraylist, arraylist1, arraylist2 };
for (int i = 0; i < 8; i++)
{
//if checkedit1 or checkedit2 is checked the checkedit3 should not be checked
if (array[i]....Checked || array[i]....Checked)
{
arraylist[i]...Checked = false;
}
else
arraylist[i]...Checked = true;
}
}
I tried to do something like this so that I don't have to write checkRow () for every row
Assuming you're not using DataGridView
or some other way of organizing them into logical strings, why don't you do the following:
Store the checkboxes in an array so you can easily access them.
CheckBox[,] checkArray = new CheckBox[8,3]...
Store the row index in the property of the Tag
first and second checkboxes.
checkBox01.Tag = 0; checkBox02.Tag = 0; checkBox11.Tag = 1; checkBox12.Tag = 1;
All the first and second flags have the same event handler:
checkBox01.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox02.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox11.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
checkBox12.CheckedChanged += new EventHandler(aCheckBox_CheckedChanged);
In the event handler, you now know exactly which checkbox to update and should no longer loop:
private void aCheckBox_CheckedChanged(object sender, EventArgs e)
{
int rowIndex = (int)((CheckBox)sender).Tag;
checkArray[rowIndex,2].Checked = !(checkArray[rowIndex,0].Checked ||
checkArray[rowIndex,1].Checked);
}
You can also do this using string queries with the checkbox name, but this is certainly slower and painful to refactor later if you decide to rename the checkboxes.
source to share
You must use the same method as the handler for all three delegates.
chkbox.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox2.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
chkbox3.CheckedChanged += new EventHandler(chkbox_CheckedChanged);
private void chkbox_CheckedChanged(object sender, EventArgs e)
{
// do your stuff here
}
source to share