How to delete a role programmatically in c#

Roles.DeleteRole(String, Boolean) Method
.Net framework Roles.DeleteRole() method allow us to remove a role from the data source. Roles class DeleteRole() method exists in System.Web.Security namespace. DeleteRole(String, Boolean) method require to pass two parameters named 'roleName' and 'throwOnPopulatedRole'.

'roleName' parameter value data type is System.String which represents the name of the role to delete. 'throwOnPopulatedRole' parameter value data type is System.Boolean. if we set this parameter value to 'true', then method throws an exception if 'roleName' has one or more members.

DeleteRole() method throw System.ArgumentNullException, if 'roleName' is null. this method throw System.ArgumentException exception, if 'roleName' is an empty string. it also throw System.Configuration.Provider.ProviderException, if 'roleName' has one or more members and 'throwOnPopulatedRole' parameter value is 'true' or Role management is not enabled.

if we pass the 'throwOnPopulatedRole' parameter value as 'false', then the role will be deleted whether it is empty or not.

the following c# example code demonstrate us how can we delete a role programmatically at run time in an application.

<%@ Page Language="C#" %>

<!DOCTYPE html>

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

    protected void DropDownListDataBind() {
        DropDownlist1.DataSource = Roles.GetAllRoles();

    protected void Button1_Click(object sender, System.EventArgs e) {
        Roles.DeleteRole(DropDownlist1.SelectedItem.Text.ToString(), false);
        Label1.Text = "Selected role deleted successfully!";

<html xmlns="">
<head runat="server">
    <title>DeleteRole method example: how to delete a role programmatically in</title>
    <form id="form1" runat="server">
        <h2>DeleteRole method example</h2>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="DarkMagenta"></asp:Label>
        <br /><br />
        <b>Select a role for delete it.</b>
        <asp:DropDownList ID="DropDownlist1" runat="server"></asp:DropDownList>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Delete selected role" OnClick="Button1_Click" />

Related examples