Disable Controls Based on Role
Most web applications need the ability to disable or hide certain contols based on what security role a user in logged in with - Admins will have more privelages then a general user.
It's pretty easy to do with .NET because they have built in the functionality to get a user's roles:
If Roles.IsUserInRole("admin") Then'Execute thisElse'Execture something elseEnd If
Finding Controls in a FormView
What I wanted to do was disable the Delete button on a Formview when the user wasn't logged in as an admin. The first thing I needed to do was actually find the control. The problem is that ASP.NET doesn't know what type of control the formView control is, so you can't directly access the properties of the control. You have to tell it (using cast) what kind of control it is.
I was looking for my Delete button:
Once you use DirectCast to tell .NET the type of control you have access to all of it's properties. This works with all of the controls - not just buttons.
Putting it Together
Another thing to note when adjusting properties of a FormView control is that you want to do it during the ItemCreated event. It won't work during the PageLoad or PreRender events. So, if you want to disable a button in a FormView based on the users role:
Protected Sub FormView1_ItemCreated(ByVal sender As Object, ByVal e As System.EventArgs) Handles FormView1.ItemCreatedIf Roles.IsUserInRole("admin") Then DirectCast(FormView1.FindControl("DeleteButton"), Button).Enabled = "True"Else DirectCast(FormView1.FindControl("DeleteButton"), Button).Enabled = "False"End IfEnd Sub
Remember Me
Powered by: newtelligence dasBlog 1.8.5223.2
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2010, Zenmonkeys
E-mail