C# 从包含2个相同ascx调用的aspx获取控件集合
嘿,我有点困难,我会感谢任何人的帮助。:D 我有一个aspx页面,该页面注册了一个ascx控件,该控件包含许多其他asp控件。在同一个aspx中的两个位置调用此ascx控件。类似如下:C# 从包含2个相同ascx调用的aspx获取控件集合,c#,asp.net,C#,Asp.net,嘿,我有点困难,我会感谢任何人的帮助。:D 我有一个aspx页面,该页面注册了一个ascx控件,该控件包含许多其他asp控件。在同一个aspx中的两个位置调用此ascx控件。类似如下: <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <table ID="Tbl1" runat="server"> <tr> &l
<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>
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 + " ";
}
}
ControlCollection controls = FindControlRecursive(this.Page, "Tbl1").Controls;
但它找不到“Tbl1”和“Tbl2”控件。我怀疑这是因为我需要指示ClientID而不是“ID”,但我不知道如何指示。
(标签控件仅用于列出找到的控件集合)
如果有人知道怎么做,我将非常感谢你的帮助
提前感谢。FindControl失败的原因是您有母版页。Rick Strahl写了一篇关于这个问题的博客,他提出了一个很好的
FindControlRecursive
函数,您可以使用它。在您的情况下,您可以这样称呼它:
<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>
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 + " ";
}
}
ControlCollection controls = FindControlRecursive(this.Page, "Tbl1").Controls;
摘自Rick Strahl的:
//
///递归地查找控件。注意:找到第一个匹配项并存在
///
///
///
///
公共静态控件FindControlRecursive(控件根,字符串Id)
{
if(Root.ID==ID)
返回根;
foreach(Root.Controls中的控制Ctl)
{
Control FoundCtl=FindControlRecursive(Ctl,Id);
如果(FoundCtl!=null)
返回FoundCtl;
}
返回null;
}
你把事情复杂化了
它与(在我的电脑上工作)一样简单:
当您知道它在哪个用户控件中时,为什么要这样做?还没有尝试过。今天晚上下班后我要试一试。10倍多。:)它可以工作,但不是我希望的那样。是否可以为每次调用ascx控件获取从ascx生成的控件集合???(此函数仅获取“cc1:Tagname1”控件,我希望获取这些控件中包含的控件集合(“cc1:Tagname1”))。10倍于您的时间。:)