The problem is you keep using Array
. Stop using that. It is designed for when you truly have generic things and in this case you don't. Array
is almost never needed.
If I understand your request correctly you have a list of checkboxes named LevelCheckBox##
. When a checkbox is checked all previously numbered ones are auto-checked. When it is unchecked all lower level check boxes are also unchecked. This isn't too hard to implement and you don't need Array
to do it.
private void OnChecked ( object sender, EventArgs e )
{
var target = sender as CheckBox;
//Get the target's ID
var targetId = GetId(target);
//To save a little time, get all checkboxes, and their "number"
// filtering out those checkboxes that don't have one
var checkBoxes = from c in Controls.OfType<CheckBox>()
let id = GetId(c)
where id >= 0
select new { Id = id, Control = c };
//If the check box is now checked
if (target.Checked)
{
//Get all the "earlier" check boxes and uncheck them
var items = checkBoxes.Where(x => x.Id < targetId);
foreach (var item in items)
item.Control.Checked = true;
} else
{
//Get all the later check boxes and uncheck them
var items = checkBoxes.Where(x => x.Id > targetId);
foreach (var item in items)
item.Control.Checked = false;
};
}
private static int GetId ( Control control )
{
//This is slow so using Tag or something would be preferable
var match = s_regex.Match(control.Name);
if (match.Success && Int32.TryParse(match.Groups["id"]?.Value, out var id))
return id;
return -1;
}
private static Regex s_regex = new Regex(@"^LevelCheckBox(?<id>\d+)$", RegexOptions.Singleline|RegexOptions.IgnoreCase);
Note that I wrote this code based upon your existing logic of using field names. Personally I would recommend you use something more maintainable such as a Tag value or perhaps just use the TabIndex. But the code I posted works irrelevant of how you determine the "less" and "greater" controls.