How to get all users in a role in c#

Roles.getUsersInRole() Method
.Net framework Roles.GetUsersInRole() method allow us to get a list of users in the specified role. Roles class GetUsersInRole() method exists in System.Web.Security namespace.

GetUsersInRole() method has a required parameter named 'roleName'. the 'roleName' parameter value data type is System.String. this string value represents the role to get the list of users for.

GetUsersInRole() method return value is System.String[] which represents a string array containing the names of all the users who are members of the specified role.

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

the following c# example code demonstrate us how can we get all users in a specified 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) { 
            ListBox1.DataSource = Roles.GetAllRoles();

    protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
        ListBox2.DataSource = Roles.GetUsersInRole(ListBox1.SelectedItem.Text.ToString());

<html xmlns="">
<head id="Head1" runat="server">
    <title>GetUsersInRole method example: how to get all the users in a role programmatically</title>
    <form id="form1" runat="server">
        <h2>GetUsersInRole method example</h2>
        <b>All Roles</b>
        <br />
        <asp:ListBox ID="ListBox1" runat="server" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>
        <br /><br />
        <b style="color:Red">All users in selected role</b>
        <br />
        <asp:ListBox ID="ListBox2" runat="server"></asp:ListBox>

Related examples