I’m attempting to replace populating an array (named "_Checks") using hard coded values with programmatically populating the array values. The array elements are CheckBox.name for all of the checkBoxes on a winForm form.
The form has 10 rows of controls with each row's controls' enablement triggered by the state of the leading checkbox. Checking a lower level box “activates” all rows above it and deselecting a higher level box “deactivates” all rows (if any) below it.
The following code is working:
private CheckBox[] _Checks;
public PrizeTemplateWRKG()
{
InitializeComponent();
_Checks = new CheckBox[]
{ LevelCheckBox00, ..., LevelCheckBox09 }; //array population via hard code [10 elements]
}
private void LevelCheckBox_CheckedChanged(object sender, EventArgs e)
{
int mstrTag = Convert.ToInt32((sender as CheckBox).Tag);
// logic for identifying checking or unchcking; excluded as irrelevant
HandleCheckboxes(mstrTag);
}
private void HandleCheckboxes( int mstrTag)
{
// wrap following in checking/unchcking logic; excluded as irrelevant
for (int x = 0; x <= mstrTag; x++)
{ _Checks[x].Checked = true; }
}
I initially tried
CheckBox[] cbArray = (CheckBox[])Controls.OfType<CheckBox>().OrderBy(x => x.Name);
which won't complie (error: Cannot convert type
'System.Linq.IOrderedEnumerable<System.Windows.Forms.CheckBox>' to 'System.Windows.Forms.CheckBox[]')
Then tried:
List<CheckBox> cbList2 = (List<CheckBox>)Controls.OfType<CheckBox>().OrderBy(x => x.Name);
which will compile but throws an exception at run-tiime:
System.InvalidCastException: Unable to cast object of type 'System.Linq.OrderedEnumerable
2 [System.Windows.Forms.CheckBox,System.String]' to type 'System.Collections.Generic.List1[System.Windows.Forms.CheckBox]'.
TL;DR I am able to find the checkboxes and create lists of checkbox names (which I intend to convert to an array with ToArray) but regardless of how I format extraction from Control.ControlCollection I end up with a string list/array and cannot convert the string to a Checkbox[] containing checkbox names. The closest I've come is using the Converter<TInput,TOutput> approach trying with both lists and arrays:
_cbList = convrtR.ConvertAll(new Converter<string, CheckBox>(stringTOcheckbox));
public static CheckBox stringTOcheckbox( string slist2cblist)
{ return new CheckBox(); }
but the result is an array populated with “System.Windows.Forms.CheckBox, CheckState: 0” elements.
Any help will be appreciated.