FindControl in RoleGroup in LoginView
I cannot find the control in the login view.
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>
And the code behind:
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;
}
}
With the user in the correct role, I can see the checkboxes, but the code behind doesn't populate them, the result of findcontrol is null.
What am I missing? Thank.
Edit . It looks like my problem was, when I do .FindControl
, the loginview username is not displayed on the screen and returns null. By placing my code on a button and calling it after the page is displayed on the screen, it works as I expected.
Edit 2 . Seems like the best place to put the code wasSuperUserLV_ViewChanged
source to share
The built-in FindControl method only searches directly for child controls. You will need to write a recursive version of the method to find all descendants. Below is an untested example that probably needs some optimization:
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;
}