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;
}
You're missing one more check, right here:
if (control.HasControls())
{
var result = GetTextBoxByID(control.Controls, id);
if (result != null)
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With