代码之家  ›  专栏  ›  技术社区  ›  TestSubject09

从包含2个对同一ascx调用的aspx获取控件集合

  •  1
  • TestSubject09  · 技术社区  · 15 年前

    嘿,我有点紧张,我会感谢任何人的帮助。

    我有一个ASPX页,它注册了一个包含许多其他ASP控件的ascx控件。此ascx控件在同一个ASPX中的两个位置调用。如下所示:

    <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”控件,我怀疑这是因为我需要指示clientid而不是“id”,但我不知道如何指示。 (标签控件仅用于列出找到的控件集合)

    如果有人知道怎么做,我会非常感谢你的帮助。

    事先谢谢。

    2 回复  |  直到 15 年前
        1
  •  1
  •   Dan Dumitru    15 年前

    你太复杂了。

    它和(在我的电脑上工作)一样简单:

    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
  •  2
  •   Darin Dimitrov    15 年前

    原因 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;
    }