I have a recursive Function, which recurses through all the Controls on
the Windows form, checks if there is an Error Message Associated with a
textbox, and then returns a bool.
How do I break out of the recursive function the first instance an
error message is encountered? What am I doing wrong? Here is the code
below -
public bool RX(Control Ctrlx)
{
bool InvalidIPX = false;
try
{
foreach (Control G in Ctrlx.Controls)
{
if (G is TextBox)
{
if (ErrorProvider.GetError(Ctrl).Length != 0)
{
InvalidIPX = true;
break;
}
}
RX(G);
}
return InvalidIPX;
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception Caught", ex);
return InvalidIPX;
}
}
Loading
Robert RybczynskiPosted Feb 11, 2008, 3:02 PM
You need to check the return value from your recursive call and break out of the caller's loop if it returns the "I quit" value (I think it's == true in this case). Otherwise, you are only unwinding the stack to the level of the caller and the recursive function simply picks up with the next control.
Rob
Guest UserPosted Jan 16, 2008, 8:35 PM
I would suggest creating a class-level boolean variable (let's call it "foundError"), set it to false before starting the recursion, then set it to true when an error condition is discovered, and then check it before calling the recursive function.
sanPosted Jan 15, 2008, 11:12 AM
Here is my code -
public bool RX(Control Ctrlx)
{
bool InvalidIPX = false;
foreach (Control G in Ctrlx.Controls)
{
if (G is TextBox)
{
if (ErrorProvider.GetError(G).Length != 0)
{
InvalidIPX = true;
break;
}
}
else
{
RX(G);
}
}
return InvalidIPX; //Once it reaches here, I want to end the function. Right now it // goes back to RX(G)
}
When I step through it everything looks good, but when try to return the InvalidIPX it goes back to RX(G). I just want to return the bool and exit out of the function, stop the iteration. Something wrong with my logic?
Guest UserPosted Jan 14, 2008, 6:00 PM
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox tb = (TextBox)c;
// validate tb contents here
}
}