2012-05-27 4 views
1

Salut j'ai besoin de faire celui-ci dans une boucle, mais je n'ai aucune idée de comment faire. Je ne peux pas le faire simplement en l'augmentant.Comment écrire une liste de tableau dans une boucle 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 
}; 

Répondre

0

Vous ne pouvez pas faire de nouvelles puis

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

il est deux manières différentes de définir un tableau. que vous devez faire:

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

Si vous voulez que cela fonctionne.

Bonne chance.

4

Si vous savez que les cases à cocher sont tous sur un formulaire:

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(); 

Si vous ne savez pas où les contrôles sont alors vous devrez chercher.

BTW: Le code ci-dessus utilise WinForms. Si vous utilisez WPF, Silverlight, Metro, ... le conteneur sera nommé différemment.

0

Dans 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); 
    } 
} 
Questions connexes