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
sanPosted Jan 17, 2008, 5:35 PM
Joel CochranPosted Jan 17, 2008, 5:19 PM
var q = from c in this.Controls.Cast
.Where(c => !"".Equals(errorProvider1.GetError(c)))
select c;
return (q.Count() > 0);
I posted at my blog about this approach. Thanks for getting me thinking!
AndyPosted Jan 16, 2008, 3:24 PM
sanPosted Jan 16, 2008, 12:22 PM
Thanks for your reply, I`m gonna try your fix too , I`ll let you know how it goes.
public bool CheckErrorsPresent(Control Ctrlx)
{
bool InvalidBool = false;
try
{
foreach (Control G in Ctrlx.Controls)
{
if (G is TextBox)
{
InvalidBool = (ErrorProvider.GetError(G).Length != 0);
}
else
{
InvalidBool = CheckErrorsPresent(G);
}
if (InvalidBool)
{
break;
}
}
return InvalidBool;
}
catch (Exception ex)
{
Console.WriteLine("{0} Exception Caught in CheckErrorsPresent", ex);
return false;
}
}
AndyPosted Jan 16, 2008, 9:49 AM
{
foreach (Control G in Ctrlx.Controls)
{
if (RX(G))
return true;
if (G is TextBox && ErrorProvider.GetError(Ctrl).Length != 0)
return true;
}
return false;
}
What kind of exception were you expecting?
AlanPosted Jan 15, 2008, 4:57 PM
Try replacing this line;
RX(G);
with the following:
if (RX(G))
{
InvalidIPX = true;
break;
}
sanPosted Jan 15, 2008, 11:17 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 return the bool and exit out of the function, stop the iteration. Something wrong with my logic?
Scott LyslePosted Jan 14, 2008, 6:56 PM
{
return true;
}