I have a winform with two checkboxes and a button. On the CheckedChanged event of both checkboxes i had given the following code.
//Enable the button if any of the checkbox is checked
var ChkBoxes = from CheckBox ctrl in this.Controls
where ctrl is CheckBox select ctrl;
button1.Enabled = ChkBoxes.Any(c => ((CheckBox)c).Checked);
but when checking either of the checkboxes I am getting an error "Unable to cast object of type 'System.Windows.Forms.Button' to type 'System.Windows.Forms.CheckBox'." the error comes up while executing the second line of code.
Later I updated the code to the following, which works fine. The only change I made is modified ctrl type from CheckBox to Control.
var ChkBoxes = from Control ctrl in this.Controls
where ctrl is CheckBox select ctrl;
button1.Enabled = ChkBoxes.Any(c => ((CheckBox)c).Checked);
My question is, in both cases I am returning controls only of type checkbox, then how come the cast error comes up. Can anyone explain me how this works?
Instead of using:
var ChkBoxes = from CheckBox ctrl in this.Controls where ctrl is CheckBox select ctrl;
Try using Enumerable.OfType<T> to do your filtering:
var chkBoxes = this.Controls.OfType<CheckBox>();
button1.Enabled = chkBoxes.Any(c => c.Checked); // No cast required now
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With