Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 单选按钮-如果选中测试-为什么前两种方法失败?_C#_Radio Button - Fatal编程技术网

C# 单选按钮-如果选中测试-为什么前两种方法失败?

C# 单选按钮-如果选中测试-为什么前两种方法失败?,c#,radio-button,C#,Radio Button,我想知道为什么下面没有按预期工作。。。 如果语句更改为(!ctrl.checked),则返回所有单选按钮的名称) myForm f=新的myForm() 然后,我将所有单选按钮放在一个分组框中,并使用以下代码: foreach (RadioButton c in groupBox1.Controls) { if (c.Checked) { MessageBox.Show(c.Name)

我想知道为什么下面没有按预期工作。。。 如果语句更改为(!ctrl.checked),则返回所有单选按钮的名称)

myForm f=新的myForm()

然后,我将所有单选按钮放在一个分组框中,并使用以下代码:

        foreach (RadioButton c in groupBox1.Controls)
        {
            if (c.Checked)
            {
                MessageBox.Show(c.Name);
            }
        }
它工作得很好

这里有什么区别


感谢您的帮助

我猜您的单选按钮是表单以外的控件的子控件。您需要递归地搜索单选按钮

    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);
            }
        } 
    }

基于示例代码的第一行,看起来您刚刚新建了一个表单,然后查看了
Checked
属性。是否有任何单选按钮实际默认为
true
以进行
检查
?我将一个单选按钮设置为default Checked,并按照TyCobb的建议正确检测为Checked,但如果我检查其他按钮,则不起作用。你知道我错过了什么吗。这在Vb/VBA中工作,刚从c#开始…您描述的工作流不太清楚。。。什么时候检查不同的按钮?您希望消息何时显示?
        foreach (RadioButton c in groupBox1.Controls)
        {
            if (c.Checked)
            {
                MessageBox.Show(c.Name);
            }
        }
    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);
            }
        } 
    }