Recursion Method Problem

M

Mike

Hello,

I have a recursive method that looks through an ASP.Net page to find a
control by ID. My problem is after it finds the control, breaks from the
loop and returns the control, it goes to my recursive line (if
control.HasControls call the findctl method). I think the problem lies in
that the method returns a value. Is this the case? Any ideas?

Thanks

private Control FindCtl(Control oControl, string controlID)
{
Control control = new Control();
foreach (Control ctl in oControl.Controls)
{

if (ctl.ID == controlID)
{
control = ctl;
break;
}

if (ctl.HasControls())
{
FindCtl(ctl, controlName);
}
}
return control;
}
 
M

Mike

Mark,

It finds the control however after it breaks out of the loop and then hits
return control line it goes up to FindCtl(ctl, controlName); line. I do not
know why this is happening?

Thanks
 
M

Marina Levit [MVP]

I would change it to something like:

if (ctl.HasControls())
{
control = FindCtl(ctl, controlName);

if (control != null)
break;
}
 
M

Mike

Thanks for the post. I changed my method to this:

public Control FindCtl(Control oControl, string controlID)
{
if (oControl.controlID == Id) return oControl;

foreach (Control Ctl in oControl.Controls)
{
Control FoundCtl = FindCtl(Ctl, controlID);
if (FoundCtl != null)
return FoundCtl;
}

return null;
}
 
T

TiSch

Hello,

I have a recursive method that looks through an ASP.Net page to find a
control by ID. My problem is after it finds the control, breaks from the
loop and returns the control, it goes to my recursive line (if
control.HasControls call the findctl method). I think the problem lies in
that the method returns a value. Is this the case? Any ideas?

Thanks

private Control FindCtl(Control oControl, string controlID)
{
Control control = new Control();
foreach (Control ctl in oControl.Controls)
{

if (ctl.ID == controlID)
{
control = ctl;
break;

}if (ctl.HasControls())
{
FindCtl(ctl, controlName);

}
}
return control;
}


Hi,
try this(in VB.NET):
Private Function FindCtl(ByVal id As String, ByVal ctl As Control) As
Control
For Each cControl As Control In ctl.Controls
If cControl.ID.Equals(id) Then
Return cControl
End If
'looking for subcontrols
If cControl.HasControls Then
Dim ctrl As Control = FindCtl(id, cControl)
If cControl.ID.Equals(id) Then
Return cControl
End If
End If
Next
End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top