Habip Oğuz
Habip Oğuz

Reputation: 1203

How to write a nested method to access a control inside a Windows form?

I want to reach a specific control in a form from another form. I wrote a method for this.

public static Control GetControl(string form_name, string control_name)
{
    var form = Application.OpenForms.Cast<Form>().FirstOrDefault(x => x.Name == form_name);
    var control = form?.Controls.Cast<Control>().FirstOrDefault(x => x.Name == control_name);
    return control;
}

But this only reached the first level controls in the Form. So if the control I am looking for, is inside a panel, it could not be found. To overcome this, I wrote a method like this:

public static Control GetControl(string form_name, string control_name)
{
    var form = Application.OpenForms.Cast<Form>().SingleOrDefault(x => x.Name == form_name);
    var first_level_control = form?.Controls.Cast<Control>().SingleOrDefault(x => x.Name == control_name);

    if (!(first_level_control is null))
    {
        return first_level_control;
    }
    else
    {
        Control second_level_control = null;
        var first_level = form?.Controls.Cast<Control>().ToList();
        if (first_level != null)
        {
            foreach (var cont in first_level)
            {
                var second_level = cont.Controls.Cast<Control>().SingleOrDefault(x => x.Name == control_name);
                if (!(second_level is null))
                {
                    second_level_control = second_level;
                    break;
                }
                else
                {
                    // I don't want to write Foreach's Foreach (for third level control) here again. Because this is not professional at all.
                }
            }
        }
        return second_level_control;
    }
}

The above method found the control I was looking for inside the panel inside the Form, but could not find if there was a panel inside the Form, a panel inside it, and what I was looking for inside that panel. I realized that I have to write a method that calls itself. However, I have no idea about this.

Upvotes: 1

Views: 258

Answers (1)

Atul Chaudhary
Atul Chaudhary

Reputation: 3736

It is simple please look for the concept of recursive function in c#. The recursive function is your answer. It is a function which calls itself based upon the condition you set

Upvotes: 1

Related Questions