In this article I will explain how to assign roles to users and remove roles from users and how populate user roles based on username selection in asp.net membership.
Description:
In previous post I explained clearly about create users using CreateUserWizard in asp.net membership or programmatically insert user details in membership and create or removes roles in asp.net membership. Now I will explain how to populate roles based on username selection and assign or remove roles to users based on username.
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Assign and Delete Roles to User in asp.net Membership</title>
<style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="GridviewDiv">
<table align="center">
<tr>
<td> <b>Select User:</b> </td>
<td><asp:DropDownList ID="ddlUsers" runat="server" AutoPostBack="true" onselectedindexchanged="ddlUsers_SelectedIndexChanged"/></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvRoles" runat="server" CssClass="Gridview" AutoGenerateColumns="false">
<HeaderStyle BackColor="#df5015" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRole" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role Name">
<ItemTemplate>
<asp:Label ID="lblRole" runat="server" Text="<%#Container.DataItem %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td colspan="2"><asp:Button ID="btnAssign" runat="server" Text="Assign or UnAssign" onclick="btnAssign_Click" /></td>
</tr>
</table>
<div align="center">
<asp:Label ID="lblSuccess" runat="server" Font-Bold="true"/>
<br />
<asp:Label ID="lblError" runat="server" Font-Bold="true"/>
</div>
</div>
</form>
</body>
</html>
|
using System;
using System.Drawing;
using System.Web.Security;
using System.Web.UI.WebControls;
|
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindUserDetails();
BindRoles();
}
}
// Bind User Names to Dropdownlist
protected void BindUserDetails()
{
ddlUsers.DataSource = Membership.GetAllUsers();
ddlUsers.DataTextField = "UserName";
ddlUsers.DataValueField = "UserName";
ddlUsers.DataBind();
ddlUsers.Items.Insert(0,new ListItem("--Select User--", "0"));
}
// Bind Roles to Gridview
protected void BindRoles()
{
gvRoles.DataSource = Roles.GetAllRoles();
gvRoles.DataBind();
}
// This event is used to assign roles to particular user
protected void btnAssign_Click(object sender, EventArgs e)
{
string userName = ddlUsers.SelectedItem.Text;
string[] userRoles = Roles.GetRolesForUser(userName);
string errorMessage = string.Empty;
string successMessage = string.Empty;
string roleName = string.Empty;
int i = 0;
int j = 0;
foreach(GridViewRow gvrow in gvRoles.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkRole");
Label lbl = (Label)gvrow.FindControl("lblRole");
roleName = lbl.Text;
if(chk.Checked)
{
int index = Array.IndexOf(userRoles, roleName);
if (index == -1)
{
Roles.AddUserToRole(userName, roleName);
successMessage += roleName + ", ";
j++;
}
}
else
{
int index = Array.IndexOf(userRoles, roleName);
if (index > -1)
{
// Remove the user from the role
Roles.RemoveUserFromRole(userName, roleName);
errorMessage += roleName + ", ";
i++;
}
}
}
if(errorMessage!=string.Empty)
{
if(i>1)
{
lblError.Text = userName+ " was removed from roles " +errorMessage.Substring(0, errorMessage.Length - 2);
}
else
{
lblError.Text = userName + " was removed from role " + errorMessage.Substring(0, errorMessage.Length - 2);
}
lblError.ForeColor = Color.Red;
}
else
{
lblError.Text = string.Empty;
}
if (successMessage != string.Empty)
{
if (j > 1)
{
lblSuccess.Text = successMessage.Substring(0, successMessage.Length - 2) + " roles assigned to " + userName;
}
else
{
lblSuccess.Text = successMessage.Substring(0, successMessage.Length - 2) + " role assigned to " + userName;
}
lblSuccess.ForeColor = Color.Green;
}
else
{
lblSuccess.Text = string.Empty;
}
}
// This event is used to populate checkboxes based on roles for particular user
protected void ddlUsers_SelectedIndexChanged(object sender, EventArgs e)
{
lblSuccess.Text = string.Empty;
lblError.Text = string.Empty;
string userName = ddlUsers.SelectedItem.Text;
string[] userRoles = Roles.GetRolesForUser(userName);
string rolename = string.Empty;
foreach (GridViewRow gvrow in gvRoles.Rows)
{
CheckBox chk = (CheckBox) gvrow.FindControl("chkRole");
Label lbl = (Label)gvrow.FindControl("lblRole");
rolename = lbl.Text;
int index = Array.IndexOf(userRoles, rolename);
if (index >-1)
{
chk.Checked = true;
}
else
{
chk.Checked = false;
}
}
}
|
Imports System.Drawing
Imports System.Web.Security
Imports System.Web.UI.WebControls
Partial Class VBAssignRoles
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindUserDetails()
BindRoles()
End If
End Sub
' Bind User Names to Dropdownlist
Protected Sub BindUserDetails()
ddlUsers.DataSource = Membership.GetAllUsers()
ddlUsers.DataTextField = "UserName"
ddlUsers.DataValueField = "UserName"
ddlUsers.DataBind()
ddlUsers.Items.Insert(0, New ListItem("--Select User--", "0"))
End Sub
' Bind Roles to Gridview
Protected Sub BindRoles()
gvRoles.DataSource = Roles.GetAllRoles()
gvRoles.DataBind()
End Sub
' This event is used to assign roles to particular user
Protected Sub btnAssign_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim userName As String = ddlUsers.SelectedItem.Text
Dim userRoles As String() = Roles.GetRolesForUser(userName)
Dim errorMessage As String = String.Empty
Dim successMessage As String = String.Empty
Dim roleName As String = String.Empty
Dim i As Integer = 0
Dim j As Integer = 0
For Each gvrow As GridViewRow In gvRoles.Rows
Dim chk As CheckBox = DirectCast(gvrow.FindControl("chkRole"), CheckBox)
Dim lbl As Label = DirectCast(gvrow.FindControl("lblRole"), Label)
roleName = lbl.Text
If chk.Checked Then
Dim index As Integer = Array.IndexOf(userRoles, roleName)
If index = -1 Then
Roles.AddUserToRole(userName, roleName)
successMessage += roleName & ", "
j += 1
End If
Else
Dim index As Integer = Array.IndexOf(userRoles, roleName)
If index > -1 Then
' Remove the user from the role
Roles.RemoveUserFromRole(userName, roleName)
errorMessage += roleName & ", "
i += 1
End If
End If
Next
If errorMessage <> String.Empty Then
If i > 1 Then
lblError.Text = userName & " was removed from roles " & errorMessage.Substring(0, errorMessage.Length - 2)
Else
lblError.Text = userName & " was removed from role " & errorMessage.Substring(0, errorMessage.Length - 2)
End If
lblError.ForeColor = Color.Red
Else
lblError.Text = String.Empty
End If
If successMessage <> String.Empty Then
If j > 1 Then
lblSuccess.Text = successMessage.Substring(0, successMessage.Length - 2) & " roles assigned to " & userName
Else
lblSuccess.Text = successMessage.Substring(0, successMessage.Length - 2) & " role assigned to " & userName
End If
lblSuccess.ForeColor = Color.Green
Else
lblSuccess.Text = String.Empty
End If
End Sub
' This event is used to populate checkboxes based on roles for particular user
Protected Sub ddlUsers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
lblSuccess.Text = String.Empty
lblError.Text = String.Empty
Dim userName As String = ddlUsers.SelectedItem.Text
Dim userRoles As String() = Roles.GetRolesForUser(userName)
Dim rolename As String = String.Empty
For Each gvrow As GridViewRow In gvRoles.Rows
Dim chk As CheckBox = DirectCast(gvrow.FindControl("chkRole"), CheckBox)
Dim lbl As Label = DirectCast(gvrow.FindControl("lblRole"), Label)
rolename = lbl.Text
Dim index As Integer = Array.IndexOf(userRoles, rolename)
If index > -1 Then
chk.Checked = True
Else
chk.Checked = False
End If
Next
End Sub
End Class
|
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Initial Catalog=AspMembership;Integrated Security=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
|
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="dbconnection" applicationName="SampleApplication"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="dbconnection" applicationName="SampleApplication"/>
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="dbconnection" applicationName="SampleApplication"/>
</providers>
</roleManager>
|
![]() |
|
If you enjoyed this post, please support the blog below. It's FREE! Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email. |
|||
Subscribe by RSS
Subscribe by Email
|
|||
|
|
|

Subscribe by RSS
Subscribe by Email
6 comments :
Very Very Thanks Dear All artical is very usefull
New Entire Devepoper.
Thank You So much, how to change Isapproved in membership table from true to false instead of delete user.
thanks for this artical its very nice.but I want role wise authentication for access menu like for user and admin permissions.
thanks suresh for your valuable articles
Suresh also attach the download test file .. this my advice,
Regards.
thnx for the artical