2010-02-05 43 views
8

C#Cách dễ dàng để sử dụng FindControl ("")

Hi,

Tôi đã phát triển C# ứng dụng web cho một vài năm và có một vấn đề tôi tiếp tục đến upagainst mà tôi có thể không tìm một cách hợp lý để giải quyết.

Tôi có quyền kiểm soát tôi muốn truy cập vào mã phía sau, kiểm soát này nằm sâu trong đánh dấu; burried trong ContentPlaceHolders, UpdatePanels, Panels, GridViews, EmptyDataTemplates, TableCells (hoặc bất cứ cấu trúc nào bạn thích .. điểm là nó có nhiều cha mẹ hơn là farthers cho công lý).

Làm thế nào tôi có thể sử dụng để truy cập FindControl("") kiểm soát này mà không cần làm điều này:

Page.Form.Controls[1].Controls[1].Controls[4].Controls[1].Controls[13].Controls[1].Controls[0].Controls[0].Controls[4].FindControl(""); 

Trả lời

12

Viết một phương pháp helper gọi FindControlRecursive theo quy định của Jeff Atwood mình.

private Control FindControlRecursive(Control root, string id) 
{ 
    if (root.ID == id) 
    { 
     return root; 
    } 

    foreach (Control c in root.Controls) 
    { 
     Control t = FindControlRecursive(c, id); 
     if (t != null) 
     { 
      return t; 
     } 
    } 

    return null; 
} 

http://www.codinghorror.com/blog/archives/000307.html

+0

+1 nhiệm vụ hoàn hảo cho đệ quy –

+0

Chỉ cần một bình luận cho hãy cẩn thận của các hit hiệu suất nếu bạn lạm dụng đệ quy. Chắc chắn vẫn là +1. –

+0

Chúc mừng, chỉ cần lừa :) – WillDud

3

Sử dụng đệ quy FindControl:

public T FindControl<T>(string id) where T : Control 
    { 
     return FindControl<T>(Page, id); 
    } 

    public static T FindControl<T>(Control startingControl, string id) where T : Control 
    { 
     // this is null by default 
     T found = default(T); 

     int controlCount = startingControl.Controls.Count; 

     if (controlCount > 0) 
     { 
      for (int i = 0; i < controlCount; i++) 
      { 
       Control activeControl = startingControl.Controls[i]; 
       if (activeControl is T) 
       { 
       found = startingControl.Controls[i] as T; 
        if (string.Compare(id, found.ID, true) == 0) break; 
        else found = null; 
       } 
       else 
       { 
        found = FindControl<T>(activeControl, id); 
        if (found != null) break; 
       } 
      } 
     } 
     return found; 
    } 
0

Hoặc trong LINQ:

 private Control FindControlRecursive(Control root, string id) 
     { 
      return root.ID == id 
         ? root 
         : (root.Controls.Cast<Control>() 
          .Select(c => FindControlRecursive(c, id))) 
          .FirstOrDefault(t => t != null); 
     } 
Các vấn đề liên quan