Home > OS >  Find Radio Group in Nested Controls in c# windows form
Find Radio Group in Nested Controls in c# windows form

Time:08-24

I wrote this recursive function to find name of radio button in each tab page:

private static DevExpress.XtraEditors.RadioGroup FindRadioGroupInTabPage(System.Windows.Forms.Control parentControl)
{
        if (!parentControl.HasChildren)
        {
            return null;
        }

        foreach (var ct in parentControl.Controls.OfType<System.Windows.Forms.Control>())
        {
            if (ct is DevExpress.XtraEditors.RadioGroup rdg)
            {
                return rdg;
            }
            else
            {
                FindRadioGroupInTabPage(ct);
                return null;
            }
        }

        return null;
}

But it always returns Null. What's wrong with my code?

CodePudding user response:

Use the following and in RadioButtonList change from RadioButton to DevExpress.XtraEditors.RadioGroup.

public static class ControlExtensions
{
    
    public static IEnumerable<T> Descendants<T>(this Control control) where T : class
    {
        foreach (Control child in control.Controls)
        {
            if (child is T thisControl)
            {
                yield return (T)thisControl;
            }

            if (child.HasChildren)
            {
                foreach (T descendant in Descendants<T>(child))
                {
                    yield return descendant;
                }
            }
        }
    }

    public static List<RadioButton> RadioButtonList(this Control control)
        => control.Descendants<RadioButton>().ToList();
}

Usage where this is the current form

List<RadioButton> radioButtons = this.RadioButtonList();

Can be used on say a panel

List<RadioButton> radioButtonInPanel = panel1.RadioButtonList();
  • Related