【发布时间】:2018-11-06 21:20:54
【问题描述】:
我想隐藏 FormView 控件的 ItemTemplate 中的“EditButton”。
这是我尝试过的 FormView 的 OnDataBound 代码:
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;
}
}
}
这是我得到的错误:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
也许问题是代码在整个 FormView 呈现在页面上之前执行?
如果当前用户是 SecGroup1 的成员,如何修改代码以确保 FormView 的 ItemTemplate 中的“EditButton”被隐藏?
--编辑--
这按预期工作......
if (fvPhaudDets.CurrentMode == FormViewMode.ReadOnly)
{
LinkButton editbtn = fvPhaudDets.FindControl("EditButton") as LinkButton;
if (editbtn != null && groupNames.Contains("SecGroup1"))
{
editbtn.Visible = true;
}
}
【问题讨论】:
-
哪一行会抛出你的错误?
-
它发生在“editbtn.visible = false;”上在 if 语句中。
-
感谢@dee-dee 的链接。我现在明白评估在 FormView 完全加载之前开始,但直到它才完成。因此,只需要一个简单的修改来评估按钮是否为空。我会将更改发布给可能发现此内容的其他人。
-
你也可以发布 formview asp.net UI 代码吗?