循环通过动态表单和面板,检查单选按钮是否检查

时间:2012-03-22 13:16:32

标签: c# windows

我有一个动态创建的表单,在此表单上有几个在运行时创建的单选按钮。这个窗体上有一个按钮,例如“下一个”,当用户点击下一个我要循环并检查其中一个单选按钮是否在我继续之前被检查时,我尝试了以下内容:

    void nextButton_Click(object sender, EventArgs e)
    {
        foreach (Control c in _form.Controls)
        {
            if (c is RadioButton)
            {
                RadioButton radio = c as RadioButton;

                if (radio is RadioButton)
                {
                    if (radio.Checked == true)
                    {
                        //code continue to next 
                    }
                    else
                    {
                        MessageBox.Show("You must select at least one.");
                    }
                }

            }
        } 
    }

亲切的问候 地理

3 个答案:

答案 0 :(得分:1)

您可以使用Linq使其更简单

bool checked = _form.Controls.OfType<RadioButton>().Any(rb => rb.Checked);

<强> - 编辑 -

我更新了答案以递归搜索所有控件。

bool IsChecked(Control parent)
{
    if (parent.Controls.OfType<RadioButton>().Any(rb => rb.Checked)) return true;

    foreach (Control c in parent.Controls)
        if (IsChecked(c)) return true;

    return false;
}

bool checked = IsChecked(_form);

答案 1 :(得分:0)

如果检查了其中一个无线电,则应退出循环,如果找到则添加退出条件。

 if (radio.Checked == true)
 {
      return;
 }
 else
 {
      MessageBox.Show("You must select at least one.");
 }

要查找嵌套控件,您应该使用:

 _form.Controls.Find()

答案 2 :(得分:0)

可能你的单选按钮位于面板内。因此单选按钮列在面板的控件集合中而不是表单中。试试这个:

    private static void CheckRadioButton(Control control)
    {
        foreach (Control c in control.Controls)
        {
            if (c is RadioButton)
            {
                if (((RadioButton)c).Checked == true)
                {
                    //code continue to next 
                }
                else
                {
                    MessageBox.Show("You must select at least one.");
                    return; //should be
                }
            }
            else if (c.Controls.Count > 0)
                CheckRadioButton(c);
        }
    }

现在通过传递form作为参数来调用此方法。像这样左右:

void nextButton_Click(object sender, EventArgs e)
{
    CheckRadioButton(this); //or whichever form it is..
}

如果控件是单选按钮,则无需再次确认内循环。