How to create a role programmatically in c#

Roles.CreateRole() Method
.Net framework Roles.CreateRole() method allow us to add a new role to the data source. Roles class CreateRole() method exists in System.Web.Security namespace.

this method require to pass a parameter named 'roleName'. the 'roleName' parameter value data type is System.String. this string value represents the name of the role to create.

CreateRole() method throw System.ArgumentNullException, if 'roleName' is null. its also throw System.ArgumentException exception, if 'roleName' is an empty string or 'roleName' contains a comma. this method throw System.Configuration.Provider.ProviderException, if Role management is not enabled.

Roles class CreateRole() method uses the default role provider to add the specified role to the data source.

the following c# example code demonstrate us how can we create a role programmatically at run time in an application.
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<script runat="server">
    protected void Page_Load(object sender, System.EventArgs e){

    protected void Button1_Click(object sender, System.EventArgs e) { 
        if(Roles.RoleExists(TextBox1.Text.ToString())== false){
            Label1.Text = TextBox1.Text.ToString() +
                " Role created successfully!";
            Label1.Text = TextBox1.Text.ToString() +
                " Role already exists";

    protected void ListBoxDataBind() {
        ListBox1.DataSource = Roles.GetAllRoles();

<html xmlns="">
<head runat="server">
    <title>CreateRole method example: how to create a role programmatically in</title>
    <form id="form1" runat="server">
        <h2>CreateRole method example</h2>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkGoldenrod" ></asp:Label>
        <br /><br />
        <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
        <hr />
        <asp:Label ID="Label2" runat="server" Text="Role Name" AssociatedControlID="TextBox1"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" Text="*"></asp:RequiredFieldValidator>
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Create Role" OnClick="Button1_Click" />

Related examples