Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Intermediate
Feb 24, 2003



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Hiding controls defined within templates to some users

It happens frequently that you want to hide some input controls or links if the current user is not logged in (it runs with the anonymous account), or if the logged user is not a member of a specific group. For example, you may want to hide the Edit/Delete buttons to users that are not Administrators. For single controls on the page, you just programmatically set the Visible property according to your rules. However, this may seem more difficult to do if the Edit/Delete controls are defined within a template repeated for each data item bound to the parent control (a Repeater, DataList or DataGrid), because you don't have direct access to the single instances of the controls. However, the solution is very simple: you just bound the Visible property to an expression that's evaluated at runtime, when you call the parent control's DataBind method. Say for example that you want to hide a button for the anonymous user - you just have to check that User.Identity.IsAuthenticated is True, and use this value for the button's Visible property, as shown below:

<asp:DataList Runat="server" ...>
        <asp:LinkButton runat="server" Text="Edit" CommandName="Edit" 
            Visible='<%# User.Identity.IsAuthenticated %>'/>
        <!-- other controls for the template -->
In more complex scenarios, you can bind the Visible property to a Protected/Public function defined in the code-behind, that checks whether the user is authenticated and its parent group, and returns True or False accordingly. Here's the example:

<asp:LinkButton runat="server" Text="Edit" CommandName="Edit" Visible='<%# ShowAdminControls() %>'/>

In the code-behind file:

Protected Functions ShowAdminControls() As Boolean
    If User.IsInRole("BUILTIN\Administrators") AndAlso User.Identity.Name = _
        "SomeName" Then
        Return True
    End If
End Function
Marco Bellinaso
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date