Sunday, April 10, 2011

Hiding buttons in Gridview based on user.

Problem
I created a web project where I am binding the list of students to the GridView. I also enabled selection, edition and deletion. My application also involved security features where I had admin, power user and guest roles. Admin could add, edit and delete, power user could add, but can't delete, and guest user can only view the record, but the problem is I can't seem to find a way to hide the buttons depending on the user.

Impact
Can either completely hide or show the buttons.

Solution
when we bind the list to the grid view, grid view creates column and bind each field to each column, it also creates columns for each field we create for Edit, Delete, Insert or Select button. In the Item templet we have a property called Visible where we could hide or show columns. Since we don't know who the user will be until run time we have to create a method that returns the true or false depending on the user.


<ItemTemplate>
                        <asp:ImageButton ID="ImageButton1" runat="server" CausesValidation="False"
                            CommandName="Edit" ImageUrl="~/Images/database_edit.png" Text="Edit"                    Visible='<%# GetShowEditButton() %>' />
                        &nbsp;<asp:ImageButton ID="ImageButton2" runat="server" CausesValidation="False"
                            CommandName="Select" ImageUrl="~/Images/arrow_left.png" Text="Select" />
                        &nbsp;<asp:ImageButton ID="ImageButton3" runat="server" CausesValidation="False"
                            CommandName="Delete" ImageUrl="~/Images/delete.png" Text="Delete" Visible='<%# GetShowDeleteButton() %>' />
                    </ItemTemplate>

Code behind file where I created the highlighted methods.


public partial class StudentView : System.Web.UI.Page
{
    private StudentRepository _studentRepository = new StudentRepository();
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }

    protected bool GetShowDeleteButton()
    {
        String[] rolesArray = Roles.GetRolesForUser();
        if (rolesArray != null)
        {
            if (rolesArray.Contains("Admin"))
                return true;
        }
        return false;
    }

    protected bool GetShowEditButton()
    {
        String[] rolesArray = Roles.GetRolesForUser();
        if (rolesArray != null)
        {
            if (rolesArray.Contains("Admin"))
                return true;
            if (rolesArray.Contains("PowerUser"))
                return true;
        }
        return false;
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.DataSource = _studentRepository.GetAllStudents();
        GridView1.PageIndex = e.NewPageIndex;

        GridView1.DataBind();
    }
}

1 comment:

  1. Hiding buttons in Gridview based on user is a tedious process in programming ASP.NET Training

    ReplyDelete