2011-10-02 27 views
1

我試圖找出一種方法來構建一個在C#中的jQuery最接近的方法的一個稍微聰明的版本。即時通訊使用的通用方法,以找到所希望的控制,然後索引的控制鏈相當於jQuery最接近()在ASP.NET Web窗體

public static T FindControlRecursive<T>(Control control, string controlID, out List<Control> controlChain) where T : Control 
{ 
    controlChain = new List<Control>(); 

    // Find the control. 
    if (control != null) 
    { 
     Control foundControl = control.FindControl(controlID); 

     if (foundControl != null) 
     { 
      // Add the control to the list 
      controlChain.Add(foundControl);  

      // Return the Control 
      return foundControl as T; 
     } 
     // Continue the search 
     foreach (Control c in control.Controls) 
     { 
      foundControl = FindControlRecursive<T>(c, controlID); 

      // Add the control to the list 
      controlChain.Add(foundControl); 

      if (foundControl != null) 
      { 
       // Return the Control 
       return foundControl as T; 
      } 
     } 
    } 
    return null; 
} 

稱之爲

List<Control> controlChain; 
var myControl = FindControls.FindControlRecursive<TextBox>(form, "theTextboxId"), out controlChain); 

要查找的id最接近元件或鍵入

// Reverse the list so we search from the "myControl" and "up" 
controlChain.Reverse(); 
// To find by id 
var closestById = controlChain.Where(x => x.ID.Equals("desiredControlId")).FirstOrDefault(); 

// To find by type 
var closestByType = controlChain.Where(x => x.GetType().Equals(typeof(RadioButton))).FirstOrDefault(); 

將這是一個很好的方法,還是有沒有其他很酷的解決方案創造這個? 您的考慮是什麼?

謝謝!

+0

所以controlChain包含指定的ID控制所有的家長? – Magnus

+0

是的,也許麪包屑會是一個更好的名字。這只是建議如何建立這樣的方法。也許這不是最好的模式? –

+2

我不確定問題是什麼,除了「我做了這個,想法?」 – millimoose

回答

1

也許這樣的事情

public static IEnumerable<Control> GetControlHierarchy(Control parent, string controlID) 
{ 
    foreach (Control ctrl in parent.Controls) 
    { 
     if (ctrl.ID == controlID) 
      yield return ctrl; 
     else 
     { 
      var result = GetControlHierarchy(ctrl, controlID); 
      if (result != null) 
       yield return ctrl; 
     } 
     yield return null; 
    } 
} 
+0

修復了現在編譯的腳本,實際上這是我今天遇到的問題的解決方案。太感謝了! –

+0

嗨,我是ASP.NET新手我想要做同樣的事情,你可以解釋一下這段代碼是如何工作的?謝謝 – MonteCristo