Reputation: 13
I try to replace each "if" by a "for" or "while":
if (CheckObject1.Checked)
XRPC.SetMemory(8184, value);
if (CheckObject2.Checked)
XRPC.SetMemory(7848, value);
[...]
if (CheckObject20.Checked)
XRPC.SetMemory(1800, value);
I already tried this but the problem is that I don't know how to increment the number at the end of checkBox:
int current = 8184;
int X = 1;
while (current > 1800)
{
if (CheckObjectX.Checked) // regex?
XRPC.SetMemory(current, value);
X += 1;
current -= 336;
}
I don't know if a regular expression can be used for "checkBox"... Any idea?
Upvotes: 1
Views: 173
Reputation: 460138
If this is winforms you can use Controls.Find
and LINQ:
int current = 8184;
int X = 1;
while (current > 1800)
{
CheckBox CheckObjectX = this.Controls.Find("CheckObject"+X, true).OfType<CheckBox>().SingleOrDefault();
if (CheckObjectX != null && CheckObjectX.Checked)
XRPC.SetMemory(current, value);
X += 1;
current -= 336;
}
If they're all in the same parent control and not nested you can pass false
as second parameter and replace this
with the container(like myCheckBoxPanel
). That could be more efficient.
Upvotes: 3
Reputation: 2912
You should load all of the checkboxes in to a list and iterate through that. Or even better, load them in to a dictionary, with int as the key, and the checkbox as the value, so that they can be accessed 'out of order'.
Or as an alternative, use the Tag property of the checkbox to store an integer key, and then access them by finding the item with the matching int, possibly combined with the suggestion of using a dictionary.
There are lots of ways to solve this problem, but don't be using the variable name.
Upvotes: 2