How to interrupt a recursive function and return a value
I am trying to find a TextBox control in an ASP.NET page using a recursive function. When this control is found, I would like to end the function and return it.
My main problem is that I cannot 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;
}
+3
source to share
2 answers
private void button1_Click(object sender, EventArgs e)
{
Control ctrl = GetControlByName(this, "archHalfRoundWindowGroup");
}
public Control GetControlByName(Control Ctrl, string Name)
{
Control ctrl = new Control();
foreach (Control x in Ctrl.Controls)
{
if (x.Name == Name)
return ctrl=x;
if (x.Controls.Count > 0)
{
ctrl= GetControlByName(x, Name);
if (ctrl.Name != "")
return ctrl;
}
if (ctrl.Name != "")
return ctrl;
}
return ctrl;
}
+1
source to share