2009-10-25 58 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