Nithesh Nithesh - 2 months ago 7
C# Question

Clear all radio buttons in a page

I have lot of dynamically generated radio buttons in my Windows Forms project. They may be checked based on the values in a database. I want to clear all radio buttons in a button click. How can I do that?

Answer

Check this:

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