I would like to hide the "EditButton" located in the ItemTemplate of a FormView control.
Here's is the OnDataBound code of the FormView that I have tried:
protected void fvPhaudDets_OnDataBound(object sender, EventArgs e)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
PrincipalSearchResult<Principal> groups = UserPrincipal.FindByIdentity(ctx, User.Identity.Name).GetAuthorizationGroups();
IEnumerable<string> groupNames = groups.Select(x => x.Name);
string mode = fvPhaudDets.CurrentMode.ToString();
lblCrntMode.Text = mode;
if (fvPhaudDets.CurrentMode == FormViewMode.ReadOnly)
{
Button editbtn = fvPhaudDets.FindControl("EditButton") as Button;
//Determine authorization based on the user's AD security groups
if (groupNames.Contains("SecGroup1"))
{
editbtn.Visible = false;
}
else
{
editbtn.Visible = true;
}
}
}
Here is the error I get:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
Maybe the issue is that the code is being executed prior to the entire FormView being rendered on the page?
How can I modify the code to make sure the "EditButton" in the FormView's ItemTemplate is hidden if the current user is a member of SecGroup1?
--EDIT--
This works as expected...
if (fvPhaudDets.CurrentMode == FormViewMode.ReadOnly)
{
LinkButton editbtn = fvPhaudDets.FindControl("EditButton") as LinkButton;
if (editbtn != null && groupNames.Contains("SecGroup1"))
{
editbtn.Visible = true;
}
}