清除页面中的所有单选按钮

时间:2011-08-11 12:09:56

标签: c# .net winforms

我的Windows Forms项目中有很多动态生成的单选按钮。可以根据数据库中的值检查它们。我想在按钮单击中清除所有单选按钮。我怎么能这样做?

5 个答案:

答案 0 :(得分:7)

检查一下:

private void button1_Click(object sender, EventArgs e) 
{
    var cntls = GetAll(this, typeof(RadioButton));
    foreach (Control cntrl in cntls)
    {
        RadioButton _rb = (RadioButton)cntrl;
        if (_rb.Checked)
        {
            _rb.Checked = false;
        }
    }
}

public IEnumerable<Control> GetAll(Control control, Type type)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrls => GetAll(ctrls, type)).Concat(controls).Where(c => c.GetType() == type);
}

答案 1 :(得分:5)

只要_radioContainer是GroupBox,两者都会在下面执行。

private void button1_Click(object sender, EventArgs e) {

    // This will remove the radiobuttons completely...
    _radioContainer.Controls.OfType<RadioButton>().ToList().ForEach(p => _radioContainer.Controls.Remove(p));

    // Either of the below will clear the checked state
    _radioContainer.Controls.OfType<RadioButton>().ToList().ForEach(p => p.Checked = false);

    foreach (RadioButton radio in _radioContainer.Controls.OfType<RadioButton>().ToList()) {
        if (radio.Checked == true) {
            radio.Checked = false;
            break;
        }
    }
}

答案 2 :(得分:1)

我不知道是否是这种情况,但您可能将单选按钮嵌套在其他控件内。如果是这种情况,您将需要浏览所有控件的所有.Controls集合,以便找到所有控件并将其关闭。您可以使用此辅助函数来执行此操作:

    void ExecuteOnAllChildren<U>(Control c, Action<Control> T) where U : Control
    {
        c.Controls.OfType<U>().ToList().ForEach(a => T(a) );

        foreach(Control childControl in c.Controls)
            ExecuteOnAllChildren<U>(childControl, T);

    }

使用它说:

    ExecuteOnAllChildren<RadioButton>(this, a => { a.Checked = false; });

(我假设“this”是你的表格。否则将“this”替换为你想要进行所有替换的表格。)

答案 3 :(得分:1)

我遇到了类似的问题,其中没有其他答案有用。

我想初始化一个带有2个Radiobuttons的Winform对话框,这个对话框应该是未经检查的。在选择某些内容之前,用户必须做出明确的选择(如此问题:https://ux.stackexchange.com/questions/76181/radio-buttons-with-none-selected)。

问题是:第一个RadioButton(具有较低TabIndex的那个)总是被预先检查。手动取消选中一个,只检查另一个(无论是在构造函数中还是在Load事件中)。

解决方案:为TabStop设置RadioButtons属性为false。不要问我原因。

答案 4 :(得分:0)

void Button1Click(object sender, EventArgs e)
{
    foreach (Control ctrl in Controls)
    {
        if (ctrl is Panel)
        {
            foreach (Control rdb in ctrl.Controls)
            {
                if (rdb is RadioButton && ((RadioButton)rdb).Checked == true)
                {
                    ((RadioButton)rdb).Checked = false;
                }
            }
        }
    }
}

这将清除按钮单击时所有选中的单选按钮。