LoginView中的RoleGroup中的FindControl

时间:2008-12-16 18:10:30

标签: c# asp.net

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

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的结果为null。

我错过了什么?感谢。

编辑:看起来我的问题是当我正在进行.FindControl登录视图未呈现到屏幕并返回null时。将我的代码放在一个按钮上,并在页面呈现到屏幕后调用它,它就像我期望的那样工作。

修改2 :似乎放置代码的最佳位置是SuperUserLV_ViewChanged

1 个答案:

答案 0 :(得分:2)

内置的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;
}
相关问题