0

我有一个登录控件,并且在标题控件中嵌套了 2 层,即页面 --> 标题控件 --> 登录控件。我无法使用 FindControl 获得对页面上控件的引用。我希望能够设置控件的可见属性,例如

  if (_loginControl != null)
            _loginControl.Visible = false;

我最终使用递归 FindControl 方法来查找嵌套控件。

    public static Control FindControlRecursive(Control root, string id)
    {
        if (root.ID == id)
        {
            return root;
        }

        foreach (Control c in root.Controls)
        {
            Control t = FindControlRecursive(c, id);
            if (t != null)
            {
                return t;
            }
        }

        return null;
    }
4

5 回答 5

0

一个好方法是使用:

Page.FindControl() 

如果产生 null,则控件不存在。

于 2010-09-15T17:47:12.250 回答
0

尝试调用 this.FindControl("_loginControl") 或 this.Page.FindControl("_loginControl")。

有关方法详细信息,请参阅 MSDN:http: //msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol.aspx

于 2010-09-15T17:48:35.597 回答
0

您是否需要从它所在的 ASP.NET 页面中禁用/隐藏用户控件(或者说,用户控件是否存在于母版页上)?如果它在同一页面中,那么在您的 ASP.NET 页面的代码隐藏中,您将执行以下操作:

MyUserControlsID.Visible = false

其中 MyUserControl 是您的用户控件的 ID。要确定用户控件的 ID,请查看 .aspx 页面的标记,您将看到如下内容:

<uc1:UserControlName ID="MyUserControlsID" runat="server" ... />

快乐编程!

于 2010-09-15T17:49:17.960 回答
0

登录控件(如果已在标记中注册)也将是代码隐藏页面的实例成员;您可以从代码隐藏类中引用它,就像它是普通成员一样,使用您提供的 ID 相同的名称(我建议对大多数逻辑使用代码隐藏,而不是在标记中内联代码,顺便说一句)。

您还可以使用页面的 FindControl() 方法,该方法将在其控件子树中搜索具有给定 ID 的控件。这需要更长的时间,所以我会推荐第一个选项,除非动态添加逻辑控制并且您并不总是知道它在那里。

于 2010-09-15T17:50:33.460 回答
0
private List<Control> GetAllNestedUserControl(Control ph)
    {
        List<Control> Get = new List<Control>();
        foreach (var control in ph.Controls)
        {
            if (control is UserControl)
            {
                UserControl uc = control as UserControl;
                if (uc.HasControls())
                {
                   Get =  GetAllNestedUserControl(uc);

                }
            }
            else
            {
                Control c = (Control)control;
                if (!(control is LiteralControl))
                {
                     Get.Add(c);
                }
            }
        }
        return Get;
    }

只需从您的任何父页面调用此代码,然后通过以下代码获得任何控制

        List<Control> Get = GetAllNestedUserControl(ph);
        Label l = (Label)Get.Find(o => o.ID == "lblusername");
        l.Text = "changed from master";
于 2014-06-12T10:44:04.350 回答