开发者

Checkbox validation with LINQ

开发者 https://www.devze.com 2023-02-11 06:13 出处:网络
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

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<开发者_如何学PythonCheckBox>() select chkbox).Any(b => b.Checked);


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

Should do the trick!


Try this:

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


Count can return the number of checked Checkboxes:

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


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;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号