单选按钮 - 检查是否已选中 - 为什么前两种方法会失败?

3

我在想为什么以下代码没有按照预期工作... 如果 if 语句改为 (!ctrl.checked),它将返回所有单选按钮的名称。

myForm f = new myForm();

        foreach (RadioButton ctrl in f.Controls.OfType<RadioButton>())
        {
            if (ctrl.Checked)
                MessageBox.Show(ctrl.Name);
        }

我也尝试过。
        foreach (Control c in f.controls)
            if (c is radiobutton)
            {
                if (c.Checked)
                {
                    messagebox.show(c.name);
                }

当我将所有单选按钮放入一个组框中,并使用以下代码时:
        foreach (RadioButton c in groupBox1.Controls)
        {
            if (c.Checked)
            {
                MessageBox.Show(c.Name);
            }
        }

它正常工作。

这里有什么区别。

感谢任何帮助。


2
根据示例代码的第一行,看起来你只是新建了一个表单,然后查看了 Checked 属性。是否有任何单选按钮默认为 trueChecked 属性? - TyCobb
1个回答

0
我猜测你的单选按钮是除了表单之外的控件的子元素。你需要递归搜索单选按钮。
    public void DisplayRadioButtons()
    {
        Form f = new Form();
        RecursivelyFindRadioButtons(f);
    }

    private static void RecursivelyFindRadioButtons(Control control)
    {
        foreach (Control childControl in control.Controls)
        {
            RecursivelyFindRadioButtons(childControl);
            if (childControl is RadioButton && ((RadioButton) childControl).Checked)
            {
                MessageBox.Show(childControl.Name);
            }
        } 
    }

我将一个单选按钮设置为默认选中,并且正如TyCobb建议的那样,它被正确地检测为已选中,但是如果我选中另一个按钮,则不起作用。你知道我错过了什么吗?这在Vb/VBA中有效,但刚开始使用c#... - user3873139
你所描述的工作流程不是很清晰... 你什么时候检查不同的按钮?你希望消息何时出现? - Kim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接