Introduction: 
In this article I will explain how to create new roles and delete roles in asp.net membership.
Description:
In previous post I explained clearly how to install asp.net membership database schema in SQL Server and create users programmatically in asp.net membership. Now I will explain how to create new roles and delete existing roles in asp.net membership.
In this article I will explain how to create new roles and delete roles in asp.net membership.
Description:
In previous post I explained clearly how to install asp.net membership database schema in SQL Server and create users programmatically in asp.net membership. Now I will explain how to create new roles and delete existing roles in asp.net membership.
Now open visual studio and create new web application and write following code in your aspx page 
| 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
<title>Create and Delete Roles 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>Enter   RoleName:</b> </td> 
<td><asp:TextBox ID="txtRole"   runat="server"/></td> 
</tr> 
<tr> 
<td></td> 
<td><asp:Button ID="btnCreate"   runat="server"   Text="Create   Role" onclick="btnCreate_Click" /></td> 
</tr> 
<tr> 
<td colspan="2"><asp:Label ID="lblResult"   runat="server"   Font-Bold="true"/></td> 
</tr> 
<tr> 
<td colspan="2"> 
<asp:GridView ID="gvRoles"   runat="server"   CssClass="Gridview"   AutoGenerateColumns="false"   AutoGenerateDeleteButton="true" onrowdeleting="gvRoles_RowDeleting"> 
<HeaderStyle BackColor="#df5015" /> 
<Columns> 
<asp:TemplateField HeaderText="Role Name"> 
<ItemTemplate> 
<asp:Label ID="lblRole"   runat="server"   Text='<%#Container.DataItem   %>'/> 
</ItemTemplate> 
</asp:TemplateField> 
</Columns> 
</asp:GridView> 
</td> 
</tr> 
</table> 
</div> 
</form> 
</body> 
</html> | 
Now add the following namespaces in code behind
C# Code
| 
using System; 
using System.Drawing; 
using System.Web.Security; 
using System.Web.UI.WebControls; | 
After that write the following 
| 
protected void   Page_Load(object sender, EventArgs e) 
{ 
if(!IsPostBack) 
{ 
BindRolesDetails(); 
} 
} 
// This Method is used to bind   roles  
protected void   BindRolesDetails() 
{ 
gvRoles.DataSource = Roles.GetAllRoles(); 
gvRoles.DataBind(); 
} 
// This Button Click event is   used to Create new Role 
protected void   btnCreate_Click(object sender, EventArgs e) 
{ 
string roleName = txtRole.Text.Trim(); 
if(!Roles.RoleExists(roleName)) 
{ 
Roles.CreateRole(roleName); 
lblResult.Text = roleName + " Role Created Successfully"; 
lblResult.ForeColor = Color.Green; 
txtRole.Text = string.Empty; 
BindRolesDetails(); 
} 
else 
{ 
txtRole.Text = string.Empty; 
lblResult.Text = roleName + " Role already exists"; 
lblResult.ForeColor = Color.Red; 
} 
} 
// This RowDeleting event is used   to delete Roles 
protected void   gvRoles_RowDeleting(object sender, GridViewDeleteEventArgs e) 
{ 
Label lableRole = (Label)gvRoles.Rows[e.RowIndex].FindControl("lblRole"); 
Roles.DeleteRole(lableRole.Text,false); 
lblResult.ForeColor = Color.Green; 
lblResult.Text = lableRole.Text + " Role Deleted Successfully"; 
BindRolesDetails(); 
} | 
If you observe above code I used different methods those are  
Roles.GetAllRoles()- This method is used to get all the roles in membership database
Roles.CreateRole(roleName) – This method is used to create new role
Roles.DeleteRole(rolename,false)- This method is used to delete role based on rolename and parameter false is used to check rolename associated with any user or not
VB.NET Code
| 
Imports System.Drawing 
Imports System.Web.Security 
Imports System.Web.UI.WebControls 
Partial Class   VBRoles 
Inherits System.Web.UI.Page 
Protected Sub   Page_Load(ByVal sender As Object, ByVal e As   EventArgs) Handles Me.Load 
If Not IsPostBack Then 
BindRolesDetails() 
End If 
End Sub 
' This Method is used to bind   roles  
Protected Sub   BindRolesDetails() 
gvRoles.DataSource = Roles.GetAllRoles() 
gvRoles.DataBind() 
End Sub 
' This Button Click event is used   to Create new Role 
Protected Sub   btnCreate_Click(ByVal sender As Object, ByVal e As   EventArgs) 
Dim roleName As String = txtRole.Text.Trim() 
If Not   Roles.RoleExists(roleName) Then 
Roles.CreateRole(roleName) 
lblResult.Text = roleName & " Role Created Successfully" 
lblResult.ForeColor = Color.Green 
txtRole.Text = String.Empty 
BindRolesDetails() 
Else 
txtRole.Text = String.Empty 
lblResult.Text = roleName & " Role already exists" 
lblResult.ForeColor = Color.Red 
End If 
End Sub 
' This RowDeleting event is used   to delete Roles 
Protected Sub   gvRoles_RowDeleting(ByVal sender As Object, ByVal e As   GridViewDeleteEventArgs) 
Dim lableRole As Label = DirectCast(gvRoles.Rows(e.RowIndex).FindControl("lblRole"), Label) 
Roles.DeleteRole(lableRole.Text, False) 
lblResult.ForeColor = Color.Green 
lblResult.Text = lableRole.Text & " Role Deleted Successfully" 
BindRolesDetails() 
End Sub 
End Class | 
Now set database connection settings in web.config 
First set the connectionstring like this 
| 
<connectionStrings> 
<add name="dbconnection" connectionString="Data Source=SureshDasari;Initial   Catalog=AspMembership;Integrated Security=true" providerName="System.Data.SqlClient"/> 
</connectionStrings> | 
After that write the following code in system.web section
| 
<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> | 
In our web.config don’t forgot to set <roleManager enabled="true"> because this will enable us to work with roles concept in membership
Demo
| 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 | |||

 
8 comments :
It's very Useful for me.Good Material
Excellent
Srilakshmi
thank you
i have used your code many times that is very useful to me
I am having a problem understanding Forms Authentication. This is a public internet site and all users will have access to the main part of the site. However there is a subdirectory that is restricted to certain users. I know that a user is valid because they will enter a user name and password
If user name and password match then
Set this users role to student registred.
how can i resolve the problem: Cannot insert the value NULL into column 'RoleId', table 'Revenue.dbo.aspnet_Roles'; column does not allow nulls. INSERT fails. The statement has been terminated.
This is the resolution: alter table aspnet_Roles alter column RoleId add ROWGUIDCOL
ALTER TABLE aspnet_Roles ADD CONSTRAINT DF_RoleId DEFAULT newid() FOR RoleId
could you help me create a database for the above code
Note: Only a member of this blog may post a comment.