2012-09-22 95 views
0

我正在用C#製作Windows窗體應用程序。將多個組合框合併爲一個可搜索變量

我的一個表單包含5個組框,每個框內包含6個複選框。 我需要統計所有選中的複選框。

在我如下已編碼的那一刻:

​​

但是我不得不重複5次以上,然後添加所有的變量一起得到答案。我確信有一個更明智的方法可以減少代碼。

我想他們三個的組合如下:

var allRacks = groupBoxSamsung.Controls.OfType<CheckBox>().Concat(groupBoxPace.Controls.OfType<CheckBox>().Concat(groupBox780.Controls.OfType<CheckBox>()));

但如預期並沒有工作。

有沒有人知道一種方法來實現這一目標?

+0

*但這並沒有按預期那樣工作。*發生了什麼? – McGarnagle

+2

我真的很抱歉,我只是試了一遍,它的工作。 我不確定我第一次做了什麼。 – user1681394

回答

0

我需要計算所有選中的複選框。

不工作,因爲你不算數。嘗試這個。

var items = (groupBox1.Controls.OfType<CheckBox>() 
    .Concat(groupBox2.Controls.OfType<CheckBox>())) 
    .Where(ch => ch.Checked == true).Count(); 

在那裏你有你的計數。

+0

感謝Randolf。無論如何,我的代碼似乎現在可以正常工作,但我可能會改用你的代碼,因爲它似乎更清晰。 – user1681394

0

我發現在計算器上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();