关于.net的控件遍历及根据Id读取控件的问题

来源:百度知道 编辑:UC知道 时间:2024/07/12 19:37:48
一个使用了模板页的页面
在<asp:Content>里有许多的<asp:Panel>,ID是有规律的,请问在CS中如何初始化<asp:Panel>的Visible,还有如何根据传进来的ID,对应显示与此ID关联的Panel
例如:
<asp:Content ID="Content1" ContentPlaceHolderID="contentPlaceHolderMain" runat="server" >
<asp:Panel ID="p0" runat="server">xxxx</asp:Panel>
<asp:Panel ID="p1" runat="server">xxxx</asp:Panel>
<asp:Panel ID="p2" runat="server">xxxx</asp:Panel>
<asp:Panel ID="p3" runat="server">xxxx</asp:Panel>
</asp:Content>
如何在页面载入时初始化p0...p3的Visible=false;
在页面传入参数Id(比如Id=2)时p2控件显示。
楼下的答案不对,在CS中,Content1根本不是一个对象,也就是说Content1.FindControl这是错误的

在页面Page_Load事件的!IsPostback中加上
if(Request.QueryString["Id"]!=null)
{
for(int i=0;i<=3;i++){
Panel pnl=(Panel)FindControlRecursive(Page,"p"+i.toString());
if( Request.QueryString["Id"].toString()==i.toString())
{
pnl.Visible=true;
}
else
{
pnl.Visible=false;
}
}
}

//递归找控件
public 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;
}

for(int i=0;i++;i<=3;i++){
Content1.FindControl("p"+i).Visible = false;
}

------------------------