Displaying Edit button in GridView based on Role

I have a Grid View. I added AutoGenerateEditButton=True.

I want to display that button to users that belong to a certain role. If not the button is not rendered.

What do you recommend? Which event do I have to handle to accomplish that purpose?

Do I have to work with template-driven control such as ListView?


         ShowEditButton="True" />
         Visible="true" />         
         HeaderText="Title"  />         

And the GridView’s Load event:

    for (int i = 0; i < grdMovies.Columns.Count; i++)
        if (grdMovies.Columns[i] is CommandField)
            grdMovies.Columns[i].Visible = false;

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Use ButtonField with CommandName = Edit.
You can hide the column in Page_Load function based on the user’s role:

const int _editColumnIndex = 0;

void Page_Load(object sender, EventArgs e)
      grdMovies.Columns[_editColumnIndex].Visible = false;

Solution 2

Anyway take into account this more correct code:

foreach (CommandField column in grdMovies.Columns.OfType<CommandField>)
    column.Visible = false;

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply