2015-09-16 49 views
0

我有一個Index.aspx,它使用一個用戶控件「SocialElement」多次(使用不同的名稱)。如何從用戶控件中檢索其他用戶控件信息?

我想從這個用戶控件「SocialElement」中檢測有關此用戶控件在Index頁面中已存在/加載的數量。

以下是我的代碼:

的Index.aspx

<MyUserControl:SocialElement ID="Element" runat="server"/> 

    <MyUserControl:SocialElement ID="Element1" runat="server"/> 

    <MyUserControl:SocialElement ID="Element2" runat="server"/> 

SocialElement.ascx的代碼背後

protected void Page_PreRender(object sender, EventArgs e) 
{ 
    var listSocialShare = Page.Controls.OfType<SocialElement>(); 
    int number = listSocialShare.Count(); 
} 

不過,我看到了 「數」 的值始終爲零時每次通過Index.aspx加載SocialElement.ascx。

我真的從「Page.Controls.OfType()」中獲得SocialElement.ascx的總數量嗎?

如果沒有,怎麼辦?謝謝。

+0

'Page.Controls'僅適用於那些Page'的'直接子控件。你需要一個遞歸算法來遍歷孩子的孩子等 – mason

+0

嗨@mason,在我的網站,我只允許Index.aspx使用SocialElement.ascx,而其他人不能。 – user3174976

+0

這並不改變我在評論中所說的話。控件處於層次結構中,'.Controls'屬性僅返回該控件的子元素,因此您需要編寫一個算法來遍歷它們並搜索層次結構的所有級別。 – mason

回答

0

@mason是正確的需要遞歸尋找控制權。你需要循環的方法通過所有控件:

protected void Page_PreRender(object sender, EventArgs e) 
{ 
    var listSocialShare = FindControlsRecursive<SocialElement>(Page); 
    int number = listSocialShare.Count(); 
} 

private IEnumerable<T> FindControlsRecursive<T>(Control root) 
{ 
    foreach (Control child in root.Controls) 
    { 
     if (child is T) 
     { 
      yield return (T)Convert.ChangeType(child, typeof(T)); 
     } 

     if (child.Controls.Count > 0) 
     { 
      foreach (T c in FindControlsRecursive<T>(child)) 
      { 
       yield return c; 
      } 
     } 
    } 
} 
相關問題