AbrahamJP
AbrahamJP

Reputation: 3430

Checkbox validation with LINQ

As part of learning LINQ, i got stuck up with the following problem.

A windows form with N number of Checkboxes and a button. The button should be enabled only when, the user checks\selected any two checkboxes. I am trying to implement this using LINQ, but couldn't achieve the desired results.

I used the following code, but works only when any one of the Checkbox is selected.

btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Any(b => b.Checked);

Upvotes: 0

Views: 1020

Answers (4)

escargot agile
escargot agile

Reputation: 22379

Do you want the Linq expression to return true if and only if exactly 2 checkboxes are selected?

If so, this should do the trick:

btnAgree.Enabled = Controls.OfType<CheckBox>()
                           .Count(b => b.Checked) == 2;

Upvotes: 0

digg
digg

Reputation: 196

Count can return the number of checked Checkboxes:

btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;

Upvotes: 0

Numan
Numan

Reputation: 3948

btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;

Should do the trick!

Upvotes: 2

ReFocus
ReFocus

Reputation: 1521

Try this:

btnAgree.Enabled = ((from chkbox in Controls.OfType<CheckBox>() select chkbox where chkbox.Checked = true).Count >= 2)

Upvotes: 1

Related Questions