2009-10-25 55 views
1

嘿2調用ASPX控件集合,我是有點掐我爾德欣賞從anyone.:D獲取從包含相同的ascx

一點幫助我有一個註冊的aspx頁面包含了許多其他的asp controls.This ascx控件的ascx控件被稱爲在同aspx.Something 2米的地方是這樣的:

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> 

<table ID="Tbl1" runat="server"> 
    <tr> 
     <td> 
      <cc1:TagName1 ID="tag1" runat="server" /> 
     </td>    
    </tr> 
</table> 
<Table ID="tbl2" runat="server">  
    <tr> 
     <td> 
      <cc1:TagName1 ID="tag2" runat="server" /> 
     </td> 
    </tr>  
</Table> 
</asp:Content> 

我的問題是:我怎樣才能在代碼的背後ASCX將「tag1」控件中包含的控件集合以及「tag2」控件中的集合文件歸檔?

我想是這樣的:

protected void btn1_Click(object sender, EventArgs e) 
     { 
      ControlCollection collection = this.Page.FindControl("Tbl1").Controls; 
      foreach (Control cont in collection) 
      { 
       lbl1.Text = cont.ClientID + " "; 
      } 

      ControlCollection collection2 = this.Page.FindControl("Tbl2").Controls; 
      foreach (Control cont in collection2) 
      { 
       lbl2.Text = cont.ClientID + " "; 
      } 
     } 

但它不能找到「TBL1」和「TBL2」 controls.I懷疑這是因爲我需要指出的客戶端ID,而不是「ID」,但我不知道如何。 (標籤控件只上市的控件中發現的集合)

如果任何人有如何做到這一點任何想法我爾德非常提前欣賞一些help.:D

感謝。

回答

1

你是過於複雜的東西。

它的工作原理一樣簡單(我的工作電腦上):

protected void btn1_Click(object sender, EventArgs e) 
{ 
    foreach (Control cont in tag1.Controls) 
    { 
     lbl1.Text += cont.ClientID + " "; 
    } 

    foreach (Control cont in tag2.Controls) 
    { 
     lbl2.Text += cont.ClientID + " "; 
    } 
} 
2

原因FindControl失敗是因爲您有一個母版頁。裏克斯特拉爾寫了一個博客post關於這個問題,他提出了一個很好的FindControlRecursive功能,你可以使用。你的情況,你可以這樣調用它:

ControlCollection controls = FindControlRecursive(this.Page, "Tbl1").Controls; 

從裏克施特拉爾的blog摘自:

/// <summary> 
/// Finds a Control recursively. Note finds the first match and exists 
/// </summary> 
/// <param name="ContainerCtl"></param> 
/// <param name="IdToFind"></param> 
/// <returns></returns> 
public static Control FindControlRecursive(Control Root, string Id) 
{ 
    if (Root.ID == Id) 
     return Root; 

    foreach (Control Ctl in Root.Controls) 
    { 
     Control FoundCtl = FindControlRecursive(Ctl, Id); 
     if (FoundCtl != null) 
      return FoundCtl; 
    } 

    return null; 
} 
+0

爲什麼要這麼做時,你知道這是在其中的用戶控制? – GenericTypeTea 2009-10-26 07:42:09

+0

還沒有嘗試過。今天晚上我下班的時候我會試一試。 10倍很多。 :) – TestSubject09 2009-10-26 14:20:07

+0

它的工作原理,但並不完全如我所願wold.Is有可能從ascx控制的ascx控件的每次調用中生成控件的集合??(該函數只獲取「cc1:Tagname1」控件,我想獲得這些控件中包含的控件集合(「cc1:Tagname1」))。 10倍於你的時間:) – TestSubject09 2009-10-27 08:43:35