C# Foreach checkbox checked in a panel

25,659

Solution 1

solution 1:

   String str1="";
   foreach (Control c in panel1.Controls)
    {
        if((c is CheckBox) && ((CheckBox) c).Checked)                      
        str1 += c.Text+ ", "; 
    }

    str1=str1.Trim();
    str1=str1.Substring(0,str1.Length-1);
    label14.Text = str1;

Solution 2: if you want to add each checked CheckBox Item into ListView

Try This:

   listView1.Items.Clear();
   foreach (Control c in panel1.Controls)
    {
        if((c is CheckBox) && ((CheckBox) c).Checked)                      
          listView1.Items.Add(c.Text);
    }

Solution 2

you can directly get if checkbox is checked:

foreach (Control c in Controls.OfType<CheckBox>())
            {
                if (((CheckBox)c).Checked == true)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
Share:
25,659
hex c
Author by

hex c

Updated on December 08, 2020

Comments

  • hex c
    hex c over 3 years

    I am trying to check each checkbox that is checked within my panel1. Then show the item checked in label1. I can not get it to work with a panel and checkboxes...below is what i have for code. Any suggestions would be great! Thanks

    foreach (int indexChecked in panel1)
    {
                str1 += panel1.Items[indexChecked].ToString() + ", ";
                label1.Visible = true;
    }
            label14.Text = str1;