Search code examples
c#winformscheckboxcomboboxwindows-controls

How to obtain the value of a control added dynamically into Windows Form c#?


I read some articles and don't managed solved my problem, My problem is in the moment when I try obtain the value of the controls (CheckBox and ComboBox) added dynamically into Windows Form, I need know when the CheckBox is checked (or unchecked) and if the ComboBox is empty (or not) when I press a button, this button call a method in which I validate if all components are empty, I add the controls the following way:

 CheckBox box;
 ComboBox cmBox;
 for (int i = 1; i <= sumOfRegisters; i++)
 {
    box = new CheckBox();
    box.Name = "CheckBox" + i;
    box.Text = "Some text";
    box.AutoSize = true;
    box.Location = new Point(10, i * 25); //vertical

    cmBox = new ComboBox();
    cmBox.Name = "ComboBox" + i;
    cmBox.Size = new System.Drawing.Size(302, 21);
    cmBox.TabIndex = i;
    cmBox.Text = "Some Text";
    cmBox.Location = new Point(270, i * 25);

    this.groupBox.Controls.Add(cmBox);
    this.groupBox.Controls.Add(box);
}

"I add the values from database in the case of the ComboBox, I omitted this part."

I try obtain the value with a foreach:

foreach (Control ctrl in groupBox.Controls)

The problem is I don't have idea how to know if the Control (CheckBox and ComboBox) is checked or empty (as the case).

Really thanks for any help, I appreciate your time.


Solution

  • You could use the as operator, like so:

    foreach (Control ctrl in groupBox.Controls)
    {
        CheckBox checkBox = ctrl as CheckBox;
        ComboBox comboBox = ctrl as ComboBox;
    
        if (checkBox != null)   // Control is a CheckBox
        {
            if (checkBox.Checked)
            {
                // CheckBox is checked
            }
            else
            {
                // CheckBox is not checked
            }
        } 
        else if (comboBox != null)  // Control is a ComboBox
        {
            if (comboBox.Items.Count == 0)
            {
                // ComboBox is empty
            } 
            else
            {
                // ComboBox isn't empty
            }
        }
    }