2012-08-03 24 views
1

我已經爲頁面控件編寫了一個小擴展方法,用於遞歸搜索控件。但是我得到了「對象引用未設置爲對象的實例」異常。頁面控件的擴展方法 - 錯誤

而似乎page.Controls只有1個控件,並且在這個控件上我也是這個例外。

任何人有任何想法?

下面是代碼:

public static Control FindControlRecursive(this Page page, string id) 
     { 
      return Execute(page, id); 
     } 

private static Control Execute(Control root, string id) 
     { 
      if (root.ID.Equals(id)) 
       return root; 
       ControlCollection controls = root.Controls; 

      foreach (Control ctrl in controls) 
      { 
       Control FoundControl = Execute(ctrl, id); 
       if (FoundControl != null) 
        return FoundControl; 
      } 
      return null; 
     } 
    } 

更新 現在我有另一個錯誤: 時出錯:索引超出範圍。必須是非負數且小於集合的大小。參數名稱:索引...

但是,這一個引發循環中的某個地方。

+0

你知道從哪個行異常被趕?你有沒有嘗試在Visual Studio中進行調試? – 2012-08-03 12:07:20

回答

1

還有一個可能的原因在這條線:

if (root.ID.Equals(id)) 

ID屬性不爲樹中的所有必要的控制設置。我甚至懷疑頁面本身是否爲空。嘗試用類似的東西替換此行:

if (string.Equals(root.ID, id)) 
+0

哦對吧,非常感謝你! – Alnedru 2012-08-03 12:14:57

1

在我看來,ID可以爲空,並且ID.Equals()引發異常。 嘗試改變線

if (root.ID.Equals(id)) 
    return root; 

if (!string.IsNullOrEmpty(root.ID) && root.ID.Equals(id)) 
     return root;