Home > Software design >  Winforms. Why do the values in the array(contains CheckBox.Checked values) come from the end?
Winforms. Why do the values in the array(contains CheckBox.Checked values) come from the end?

Time:07-15

I get some troubles, how to fix this?

There's code:

void button1_Click(object sender, EventArgs e)
{
    List<bool> propertiesList = new();

    foreach (CheckBox checkBox in Controls.OfType<CheckBox>())
        propertiesList.Add(checkBox.Checked);

    int[] properties = new int[propertiesList.Count];

    for (int i = 0; i < properties.Length; i  )
    {
        properties[i] = propertiesList[i] ? 1 : 0;
    }

    MessageBox.Show(String.Join(", ", properties));
}

In MessageBox I got this, but it must be 1, 1, 1, 0, 0:

enter image description here

CodePudding user response:

Look in the Form1.Designer.cs file. The form design code is written there. The CheckBoxes here are created in the same order as they were added to the form, but at the end they are added to the Controls collection in reverse order.

this.Controls.Add(this.checkBox3);
this.Controls.Add(this.checkBox2);
this.Controls.Add(this.checkBox1);

Controls collection can be processsed reversely, or the result can be reversed. However, it would be better to add values to the list manually by name, or keep a sorted collection of references directly to CheckBoxes.

  • Related