如何在.aspx页面上从.ascx获取控件引用?

时间:2012-06-13 13:55:00

标签: c# asp.net

我有一个这样的向导设置:

<asp:Wizard ID="Wizard1" runat="server" DisplaySideBar="false" onnextbuttonclick="OnNextButtonClick">
       <WizardSteps>
           <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1">
            <div class="content">
                <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
            </div>
           </asp:WizardStep>
           <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2">
               <div class="content">
                   <asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
               </div>
           </asp:WizardStep> ...more

然后在该页面的预渲染中我添加控件如下:

protected void Wizard1_PreRender(object sender, EventArgs e)
{
    PlaceHolder1.Controls.Add(LoadControl("Control1.ascx"));
    PlaceHolder2.Controls.Add(LoadControl("Control2.ascx"));
    PlaceHolder3.Controls.Add(LoadControl("Control3.ascx"));
    ...more controls added
 }

在.ascx控件上我有一个我想要访问的ajaxToolkit:TabContainer:

<ajaxToolkit:TabContainer ID="TabContainer1" runat="server" ActiveTabIndex="0">  
            <ajaxToolkit:TabPanel ID="TabPanel1" HeaderText="PRV 1" runat="server">

所以我想要做的是停止向导进入下一步并将ajaxtoolkit:Tabcontainer移动到下一个选项卡。我像这样访问下一个按钮:

protected void OnNextButtonClick(object sender, WizardNavigationEventArgs e)
{
     if(Wizard1.ActiveStepIndex == 2)
     {
          e.Cancel = true;
          //get ajaxToolKit:tabcontrol here
     }
}

有关如何在OnNextButtonClick函数中访问TabControl的任何想法?这是一个asp.net webapplication。

1 个答案:

答案 0 :(得分:1)

如果您不知道页面的深度(对.ascx有用),您可以使用Page.GetControl(“TabContainer1”)或使用递归方法。

public static Control FindControlRecursive(Control container, string name)
{
    if ((container.ID != null) && (container.ID.Equals(name)))
        return container;

    foreach (Control ctrl in container.Controls)
    {
        Control foundCtrl = FindControlRecursive(ctrl, name);
        if (foundCtrl != null)
            return foundCtrl;
    }
    return null;
}

使用它FindControlRecursive(Page,“TabContainer1”)