Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate a recursive function and return a value

Tags:

c#

asp.net

I'm trying to find a TextBox control inside a ASP.NET page using a recursive function. When this control is found, i would like to terminate the function and return it.

My main problem is that i'm unable to stop the recursive function and return the control.

Here's my code:

//execute recursive function to find a control in page by its id
TextBox textbox = GetTextBoxByID(controlCollection, id);

//recursive function
private TextBox GetTextBoxByID(ControlCollection controlCollection, string id)
{
    foreach (Control control in controlCollection)
    {
        if (control is TextBox)
        {
            TextBox tb = (TextBox)control;

            if (tb.ID == id)
            {
                //return selected texbox and terminate this recursion
                return tb;
            }
        }

        if (control.HasControls())
        {
            GetTextBoxByID(control.Controls, id);
        }
    }

    //no control found return null
    return null;
}
like image 961
Ricky Avatar asked Oct 27 '25 06:10

Ricky


1 Answers

You're missing one more check, right here:

if (control.HasControls())
{
    var result = GetTextBoxByID(control.Controls, id);
    if (result != null)
        return result;
}
like image 162
walther Avatar answered Oct 28 '25 22:10

walther



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!