Hiding controls defined within templates to some users

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:


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:


Share the Post: