Reputation: 34188
i found it is possible to validate checkboxes is selected or not by linq.
i got the code like
btnAgree.Enabled = (from chkbox in Controls.OfType<CheckBox>() select chkbox).Count(b => b.Checked) >= 2;
but my scenario is like i have many check boxes on my win form but i want to check any check boxes inside my group box is selected by LINQ. is it possible but i found no way still. please help me with code.
i got a little code which is bit similar. the code as follows
public static IEnumerable<T> AllControls<T>(this Control startingPoint) where T : Control
{
bool hit = startingPoint is T;
if (hit)
{
yield return startingPoint as T;
}
foreach (var child in startingPoint.Controls.Cast<Control>())
{
foreach (var item in AllControls<T>(child))
{
yield return item;
}
}
}
var checkboxes = control.AllControls<CheckBox>();
var checkedBoxes = control.AllControls<CheckBox>().Where(c => c.Checked);
but how to customize this code that it will work with group box where my all check box is located. please guide. another issue is i am using c# v2.0. thanks
Upvotes: 1
Views: 1649
Reputation: 460058
You don't need to use form's control collection, you can use your GroupBox' control collection instead:
btnAgree.Enabled = GroupBox1.Controls.OfType<CheckBox>()
.Where(chk => chk.Checked)
.Count() >= 2;
Upvotes: 4
Reputation: 60493
if you need recursion (imagine you have a panel in your GroupBox, and checkboxes have been added to panel), I think your extension method would still be usefull
changed a bit
public static IEnumerable<T> AllControls<T>(this Control startingPoint) where T : Control
{
if (startingPoint is T)
yield return startingPoint as T;
foreach (var item in startingPoint.Controls.Cast<Control>().SelectMany(AllControls<T>))
yield return item;
}
usage :
var list = groupBox1.AllControls<CheckBox>();
var listChecked = list.Where(m => m.Checked);
Upvotes: 1
Reputation: 280
btnAgree.Enabled =
(from chkbox in groupBox1.Controls.OfType<CheckBox>()
select chkbox).Count(b => b.Checked) >= 2;
You're checking the controls of the form.
Upvotes: 4