我發現在計算器上How to get all childControls of a type on a form一個問題,它擴展到算選中的元素。
private void button1_Click(object sender, EventArgs e)
{
label1.Text = (from c in GetAll(this, typeof(CheckBox))
where (c as CheckBox).Checked
select c).Count().ToString();
}
// credits go to @PsychoCoder for this part
public IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
總的來說,我認爲這個片段應該做的伎倆,你不必Concat的所有groupBoxes!
編輯
適應於計數所有的表格上選中的複選框,無論複選框都childControls與否。
Type type = typeof(CheckBox);
var controls = this.Controls.Cast<Control>();
label1.Text = controls.SelectMany(ctrl => GetAll(ctrl))
.Concat(controls)
.Where(c => c.GetType() == type && (c as CheckBox).Checked)
.Count().ToString();
*但這並沒有按預期那樣工作。*發生了什麼? – McGarnagle
我真的很抱歉,我只是試了一遍,它的工作。 我不確定我第一次做了什麼。 – user1681394