2015-05-12 71 views
3

我試圖在遞歸函數中找到一個ASP.NET頁面內的TextBox控件。當找到這個控件時,我想終止該函數並返回它。如何終止一個遞歸函數並返回一個值

我的主要問題是,我無法停止遞歸函數並返回控件。

這裏是我的代碼:

//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; 
} 

回答

7

你錯過了一個更加檢查,就在這裏:

if (control.HasControls()) 
{ 
    var result = GetTextBoxByID(control.Controls, id); 
    if (result != null) 
     return result; 
} 
+0

你不需要是嵌套的if語句... – ohmusama

+0

@ohmusama ,你會這樣做,否則它不會遍歷所有可能的分支,但是如果返回更多的元素,則在第一次「foreach」通過後終止。 – walther

+0

你確實是對的 – ohmusama

1
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; 
    } 
+0

你能解釋你的例子嗎? – mhatch

相關問題