Displaying Edit button in GridView based on Role

2020-05-01 07:27发布

问题:

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?

Solution:

<Columns>
    <asp:CommandField 
         ShowEditButton="True" />
    <asp:BoundField 
         DataField="Id" 
         ReadOnly="true"  
         Visible="true" />         
    <asp:BoundField 
         DataField="Title" 
         HeaderText="Title"  />         
</Columns> 

And the GridView's Load event:

if(!User.IsInRole("Manager"))
{
    for (int i = 0; i < grdMovies.Columns.Count; i++)
    {
        if (grdMovies.Columns[i] is CommandField)
        {
            grdMovies.Columns[i].Visible = false;
        }
    }
}

回答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)
{
  if(!User.IsInRole("Manager"))    
      grdMovies.Columns[_editColumnIndex].Visible = false;
}


回答2:

Anyway take into account this more correct code:

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