首页 > 解决方案 > 如何隐藏asp.net FormView控件中的“编辑”按钮?

问题描述

我想隐藏位于 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;
        }
    }

标签: c#asp.netformview

解决方案


尝试这个:

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或从模板中删除按钮本身。


推荐阅读