radiobutton checked validation
I have multiple panels and on each panel I have 2 RadioButtons. I need a way to check if a radiobutton has not been selected within each panel. If the panel contains 2 radiobuttons during a loop and if those 2 radiobuttons are not selected the variable (submit) would then be set to false.
Here i开发者_开发知识库s my code so far -
foreach(Panel panels in groupBox2.Controls)
{
foreach (RadioButton radio in panels.Controls)
{
if (!radio.Checked)
{
submit = false;
}
}
}
By default each panel will only contain one radio checked it the radio buttons AutoCheck
is true, Anyway to your question:
foreach(Control parent in groupBox2.Controls)
{
Panel panel = parent as Panel;
if (panel != null)
{
foreach (Control child in panel.Controls)
{
RadioBox radio = child as RadioBox;
if (radio != null)
{
if (!radio.Checked)
{
MessageBox.Show(radio.ToString());
break;//if AutoCheck of all radio buttons seted to true
}
}
}
}
}
If you are only interested in one specific radiobutton, it would be easier to keep a global reference to it. That way you can just check the button directly whenever you'd like, rather than go through multiple loops.
Your code won't work because the Container.Controls collection contains "Control" references, so you need to check each control to see if it's the type you're looking for.
foreach(var control1 in groupBox2.Controls)
{
if (control is Panel)
{
foreach (var control2 in control1.Controls)
{
if (control2 is RadioButton)
{
if (!(control2 as RadioButton).Checked)
{
MessageBox.Show(control2.Text);
}
}
}
}
}
That will make your current code work. But I'm not quite sure what you're asking. There can only be one radiobutton selected in each containter.
if (!radM.Checked && !radF.Checked)
{
lblAnswer.Text = "Please Select male or female";
txtHT.Text = null;
}
精彩评论