2012-05-27 75 views
1

嗨,我需要做一个循环,但我不知道该怎么做。我不能仅仅通过递增来做到这一点。如何在for循环中写入数组列表?

CheckBox[] checkboxarray; 

checkboxarray = new CheckBox[] { 
    txtChckBx0, txtChckBx1, txtChckBx2, txtChckBx3, txtChckBx4, txtChckBx5, 
    txtChckBx6, txtChckBx7, txtChckBx8, txtChckBx9, txtChckBx10, txtChckBx11, 
    txtChckBx12, txtChckBx13, txtChckBx14, txtChckBx15, txtChckBx16, txtChckBx17, 
    txtChckBx18, txtChckBx19, txtChckBx20, txtChckBx21, txtChckBx22, txtChckBx23, 
    txtChckBx24, txtChckBx25, txtChckBx26, txtChckBx27, txtChckBx28, txtChckBx29, 
    txtChckBx30, txtChckBx31, txtChckBx32, txtChckBx33, txtChckBx34, txtChckBx35, 
    txtChckBx36, txtChckBx37, txtChckBx38, txtChckBx39, txtChckBx40, txtChckBx41, 
    txtChckBx42, txtChckBx43, txtChckBx44, txtChckBx45, txtChckBx46, txtChckBx47, 
    txtChckBx48, txtChckBx49, txtChckBx50, txtChckBx51, txtChckBx52, txtChckBx53, 
    txtChckBx54, txtChckBx55, txtChckBx56, txtChckBx57, txtChckBx58, txtChckBx59, 
    txtChckBx60, txtChckBx61, txtChckBx62, txtChckBx63, txtChckBx64, txtChckBx65, 
    txtChckBx66, txtChckBx67, txtChckBx68, txtChckBx69, txtChckBx70, txtChckBx71, 
    txtChckBx72, txtChckBx73, txtChckBx74, txtChckBx75, txtChckBx76, txtChckBx77, 
    txtChckBx78, txtChckBx79, txtChckBx80 
}; 

回答

0

你不能做新的,然后

checkboxarray = new CheckBox[] { txtChckBx0, ....} 

这是两种不同的方式来定义的数组。 你需要做的:

CheckBox[] checkboxarray = { txtChckBx0, ....}; 

如果你想要的工作。

祝你好运。

4

如果您知道的复选框都是一个形式:

var list = new List<CheckBox>(); 
foreach(var control in this.Controls) 
{ 
    var checkBox = control as CheckBox; 
    if(checkBox != null) 
    { 
     list.Add(checkBox); 
    } 
} 

var checkBoxArray = list.ToArray(); 

如果你不知道该控件,那么你将不得不寻找他们。

BTW:上面的代码使用WinForms。如果您使用的是WPF,Silverlight,Metro,...容器的命名方式不同。

0

在WinForm的

List<CheckBox> checkBox = new List<CheckBox>(); 
// Adding checkboxes for testing... 
for (int i = 0; i <= 80; i++) 
{ 
    var cbox = new CheckBox(); 
    cbox.Name = "txtChckBx"+ i.ToString(); 
    checkBox.Add(cbox); 
    Controls.Add(cbox); 

} 

List<CheckBox> checkBoxfound = new List<CheckBox>(); 
// loop though all the controls 
foreach (var item in Controls) 
{ 
    // filter for checkboxes and name should start with "txtChckBx" 
    if (item is CheckBox && ((CheckBox)item).Name.StartsWith("txtChckBx", StringComparison.OrdinalIgnoreCase)) 
    { 
     checkBoxfound.Add((CheckBox)item); 
    } 
}