Don Sartain

Don Sartain

  • NA
  • 15
  • 6.4k

Iterate through a control collection

Aug 1 2012 10:09 AM
I'm trying to find out how to iterate through a control collection. Specifically, I have a set of check boxes in one group box, and a set of labels in another group box. For now, I want the labels to reflect whether or not the box is checked.  The end product will be testing whether a given server is able to connect through a specific socket, and display that in the label.

Here's what I have so far:

[code]
private void frmServerChecker_Load(object sender, EventArgs e)
        {
            txtDomain.Focus(); //Text box for user to input a domain name

            /* Add Check Boxes Dynamically
                // Opted not to go this route for now
            for (int count = 0; count < 4; count++)
            {
                int y = 45;
                CheckBox[] cb= new CheckBox[count];
                    for (int i=0; i<count; i++)
                    {
                        cb[i] = new CheckBox();
                        cb[i].Location = new Point(30, y);
                        grpDiag.Controls.Add(cb[i]);
                        y += 15;
                    }
                //this.Controls.Add(cb[count]);
             }
             */

             // Add checkboxes created in Design View to group box Control Collection
            grpOptions.Controls.Add(chkHTTP);
            grpOptions.Controls.Add(chkFTP);
            grpOptions.Controls.Add(chkPOP);
            grpOptions.Controls.Add(chkSMTP);

            // Add labels created in Design View to group box Control Collection
            grpDiag.Controls.Add(lblHTTPStatus);
            grpDiag.Controls.Add(lblFTPStatus);
            grpDiag.Controls.Add(lblPOPStatus);
            grpDiag.Controls.Add(lblSMTPStatus);

        }

        private void cmdRunDiagnostics_Click(object sender, EventArgs e)
        {
           
            foreach (Control box in grpDiag.Controls)
            {
                int httpIndex = grpDiag.Controls.GetChildIndex(chkHTTP);
               
            }
        }
[/code]

                The command button code will get me the Index of the first checkbox, but I can't figure out how to check for the checkbox properties to see whether the box is checked. In VB 6, this was easy because of the Index field we could set during design time, but I can't find out how to make this something I can iterate through in a for loop (which I'll need to do).

Ideally, I'd like to be able to do something like this:

[code]
        for (int x=0; x<4; x++)
        {
                bool status[x] = checkbox[x].checked;
                if (status[x] == 1)
                {
                        label[x].Text = "Checkbox is checked";
                }

        }

[/code]

Or something like that. Please forgive any syntax issues in this example as I did it on the fly.

Answers (2)