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

在LoginView的RoleGroup中查找控件

  •  0
  • NikolaiDante  · 技术社区  · 17 年前

    我似乎在登录视图中找不到控件。

    ASPX是:

    <asp:LoginView ID="SuperUserLV" runat="server">
        <RoleGroups>
                <asp:RoleGroup Roles="SuperUser">
                        <ContentTemplate>       
                                <asp:CheckBox ID="Active" runat="server" /><br />
                                <asp:CheckBox ID="RequireValidaton" runat="server" />
                </ContentTemplate>
            </asp:RoleGroup>
        </RoleGroups>
    </asp:LoginView> 
    

    后面的代码是:

    if (Context.User.IsInRole("SuperUser"))
    {
        CheckBox active = (CheckBox) SuperUserLV.FindControl("Active");
        if (active != null)
        {
            active.Checked = this.databaseObject.Active;
        }
    
        CheckBox require = (CheckBox) SuperUserLV.FindControl("RequireValidaton");
        if (require != null)
        {
            require.Checked = this.databaseObject.RequiresValidation;
        }
    }
    

    使用正确角色的用户,我可以看到复选框,但后面的代码无法填充它们,findcontrol的结果为空。

    我错过了什么?谢谢。

    编辑 :看起来我的问题是当我 .FindControl LoginView未呈现到屏幕,正在返回空值。把我的代码放在一个按钮上,并在页面呈现到屏幕上后调用它,它会像我预期的那样工作。

    编辑2 :似乎放置代码的最佳位置是 SuperUserLV_ViewChanged

    1 回复  |  直到 17 年前
        1
  •  2
  •   Brandon Gano    17 年前

    内置的findcontrol方法只搜索直接子控件。您需要编写方法的递归版本来搜索所有子代。以下是一个未经测试的示例,可能需要进行一些优化:

    public Control RecursiveFindControl(Control parent, string idToFind)
    {
        for each (Control child in parent.ChildControls)
        {
            if (child.ID == idToFind)
            {
                return child;
            }
            else
            {
                Control control = RecursiveFindControl(child, idToFind);
                if (control != null)
                {
                    return control;
                }
            }
        }
        return null;
    }
    
    推荐文章