How to iterate over checkboxes in order from top to bottom or set the order
I have this code:
foreach (Control child in TableNamePanel.Controls)
{
if (!(child is CheckBox))
continue;
if ((child as CheckBox).Checked)
{
Code...
}
}
My designs are CheckBoxes
on top of each other and the other matters. I would like to check the first one checkbox
, then the next and so on. It currently starts from the bottom. Any way to change this, or to set the order it passes through the controls?
Change foreach
as follows:
foreach (Control child in TableNamePanel.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
{
}
This will sort Controls
according TabIndex
to the form. You may need to change OrderBy
to OrderByDescending
.
I think when you loop, they are in order, according to what they are in development
but this is not how you can set a property CheckBox.TabIndex
on a checkbox to order it
var orderedcheckbox= TableNamePanel.Controls.OfType<CheckBox>()
.OrderBy(c => c.TabIndex);
Here I assumed the tabindex property is avaialbe as far as I know this property is available in .net.
Including another solution suggested in comment from @dotNET
TabOrder of your design-time controls that it should have anyway. Another way is to use the Location property of your checkboxes instead of TabOrder in the above code.