Reputation: 1277
I'm trying to fill a checkbox array with checkbox names derived from strings. I would like to replace the following code:
public void CheckBox_1()
{
CheckBox[] boxes_1 = new CheckBox[4];
boxes_1[0] = A0;
boxes_1[1] = A1;
boxes_1[2] = A2;
boxes_1[3] = A3;
for (int i = 0;i < 4;i++)
{
boxes_1[i].Enabled = checkBox1.Checked == true ? true : false;
}
}
with something like this:
public void CheckBox_1()
{
CheckBox[] boxes_1 = new CheckBox[4];
for (int i = 0; i < 4; i++)
{
boxes_1[i] = ("A" + i);
}
for (int i = 0; i < 4; i++)
{
boxes_1[i].Enabled = checkBox1.Checked == true ? true : false;
}
}
I can get the checkbox name to a string easy enough, but it's not clear how to accomplish this. Thanks.
Upvotes: 1
Views: 903
Reputation: 356
Assuming that checkboxes could be nested inside other controls inside of some common container, this might work:
private void CheckBox_1()
{
foreach (var checkbox in FindChildren<CheckBox>(container, c => c.Name.StartsWith("A")))
{
checkbox.Enabled = checkBox1.Checked == true ? true : false;
}
}
public static IEnumerable<T> FindChildren<T>(Control parent, Func<T, bool> filter)
where T : Control
{
var search = new Stack<Control>();
search.Push(parent);
while (search.Count > 0)
{
parent = search.Pop();
foreach (Control child in parent.Controls)
{
T typed = child as T;
if (typed != null && filter(typed))
{
yield return typed;
continue;
}
search.Push(child);
}
}
}
Upvotes: 0
Reputation: 50215
You can use the Control.Controls of the containing object to get all the CheckBox
controls via OfType<T>
and then filter on the Name
s that start with "A".
var container = ...control with the checkboxes...;
foreach(var cb in container.Controls.OfType<CheckBox>().Where(c => c.Name.StartsWith("A")))
{
cb.Enabled = checkBox1.Checked;
}
Upvotes: 1
Reputation: 460028
Instead of fiddling around with reflection just to create code that is prone to errors and difficult to understand, i would suggest to group the related checkboxes in container controls like GroupBox
.
Then it's very easy and readable:
// consider renaming
public void CheckBox_1()
{
var relatedCheckBoxes = GroupBox1.Controls.OfType<CheckBox>();
foreach (var chk in relatedCheckBoxes)
chk.Enabled = checkBox1.Checked; // you might want to pass this checkbox as argument instead
}
Upvotes: 0