Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading