Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Casting issue

Tags:

c#

linq

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?

like image 861
AbrahamJP Avatar asked Mar 21 '26 05:03

AbrahamJP


1 Answers

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
like image 161
Reed Copsey Avatar answered Mar 22 '26 18:03

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!