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 this
Else
'Execture something else
End 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:
DirectCast(FormView1.FindControl("DeleteButton"), 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.ItemCreated
If Roles.IsUserInRole("admin") Then
DirectCast(FormView1.FindControl("DeleteButton"), Button).Enabled = "True"
Else
DirectCast(FormView1.FindControl("DeleteButton"), Button).Enabled = "False"
End If
End Sub