Iterate through Check Boxes
Hi all,
I have added a number of check boxes on my form and all the check boxes are added dynamically at runtime.
Now I need to iterate through all check boxes and get their name property. I used a foreach loop but the iterator isn't coming inside the loop and check boxes are remain untouched.
Any ideas ??
Thanks
Re: Iterate through Check Boxes
Code:
foreach (Control c in this.Controls)
{
if (c is CheckBox) {
MessageBox.Show(c.Name);
}
}
Something like that.
Re: Iterate through Check Boxes
Quote:
Originally Posted by crptcblade
Code:
foreach (Control c in this.Controls)
{
if (c is CheckBox) {
MessageBox.Show(c.Name);
}
}
Something like that.
Yes, I tend to add a tag property which identifies it as the control i want to modify.
Re: Iterate through Check Boxes
Thanks, this code works for me. My check boxes are in a group box, so I am using this code.
foreach(Control chk in groupBox.Controls)
{
if(chk is CheckBox)
if(chk.Name=="abc")
chk.Checked=true;
}
But I am unable to find a Checked property in chk.
I also tried this.
foreach(CheckBox chk in groupBox.Controls)
{
if(chk.Name=="abc")
chk.Checked=true;
}
Here I found the Checked property but an exception occurs, "Specified cast isnot valid".
Any ideas ??
Thanks
Re: Iterate through Check Boxes
Probably checkboxes aren't the only type of control in your groupbox.
The foreach won't filter out just the checkboxes, you need to foreach on the Control type, and check to see if the current control is a checkbox.
Re: Iterate through Check Boxes
Yes, I have labels as well. If I take chk of Control type, then I am unable to find a Checked property. May be I have to cast the chk to CheckBox, but I dont know how, am very new to C#.
Re: Iterate through Check Boxes
You need to cast the control to checkbox before you can set the checked property to true/false as not all controls has checked property like your Label control. Here is the code you need :
Code:
foreach(Control ctrl in groupBox.Controls)
{
if(ctrl is CheckBox)
{
if(ctrl.Name=="abc")
{
CheckBox chk = new CheckBox();
chk = (CheckBox)ctrl
chk.Checked=true;
}
}
}