Using LoginView on HyperLinkFields within a GridView

Posted by Ryan Baxter Wed, 13 Aug 2008 19:45:00 GMT

The title of this post is a bit misleading. Using a LoginView to manage the security of HyperLinkFields within a GridView does not work. There are, however, other means to achieve the same result.

Using the GridView’s OnRowDataBound event, I’ve set my Cells containing HyperLinkFields, on DataRows with a RowIndex of -1, to an empty string if the user does not belong to the “Administrators” role. This hides my HyperLinkFields from underprivileged users and prevents elements of my GridView’s header and footer from not appearing.

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowIndex != -1)
    {
        if (!Page.User.IsInRole("Administrators"))        
            e.Row.Cells[0].Text = String.Empty;
    }           
}

*Update

I just found a thread on the ASP.NET forums that covers the same problem. In their solution, the GridView’s RowType is checked before setting the Cell’s Visibility property to false. This makes more sense than relying on the RowIndex property to determine whether or not a DataRow’s Cell should be hidden. In the method below, I’ve integrated the DataControlRowType enumeration as suggested by the ASP.NET forums. Since setting the Visibility property of Cells containing HyperLinkFields caused my GridView headings to not line up properly, I decided to assign the Cell’s Text property to String.Empty as in my previous example.

protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{                  
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (!Page.User.IsInRole("Administrators"))
            e.Row.Cells[0].Text = String.Empty;
    }   
}
Comments

Leave a response