【问题标题】:How to hide the "Edit" button in an asp.net FormView control?如何隐藏asp.net FormView控件中的“编辑”按钮?
【发布时间】: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 代码吗?

标签: c# asp.net formview


【解决方案1】:

试试这个:

protected void fvPhaudDets_DataBound(object sender, EventArgs e)
        {
          ((LinkButton) ((FormView)sender).FindControl("EditButton")).Visible = false;// Hides Edit button
          ((LinkButton) ((FormView)sender).FindControl("NewButton")).Visible = false;// Hides New button
          ((LinkButton) ((FormView)sender).FindControl("DeleteButton")).Visible = false;// Hides Delete button
        }

另一种解决方案:编辑模板,然后将链接按钮的属性更改为Visible= false 或从模板中删除按钮本身。

【讨论】:

    猜你喜欢
    • 2016-07-16
    • 2014-04-12
    • 2010-09-07
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    相关资源
    最近更新 更多