Problem : Get a list of user belonged to a role or to know if a user already has a role

What code can I write to know if a user belonged to a Role already ? and How can I get a list of a  user already in an existing role ? Please have a look at my code below :

Protected Sub AddUsers_OnClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddUsersToRole.Click

' I wanna add some code here to check if a user already belonged to a Role
' Please insert your code here. Thanks a lot.

' A role must be selected

If RolesListBox.SelectedItem Is Nothing Then
Msg.Text = "Please select a role."
Exit Sub
End If

' At least one user must be selected

If UsersListBox.SelectedItem Is Nothing Then
Msg.Text = "Please select one or more users."
Exit Sub
End If

' Create list of users to be added to the selected role

Dim sizeOfArray As Integer = UsersListBox.GetSelectedIndices.Length
Dim newUsers(sizeOfArray - 1) As String

'For i As Integer = 0 To newusers.Length - 1

' newusers(i) = _

' UsersListBox.Items( _

' UsersListBox.GetSelectedIndices( )(i)).Value


For i As Integer = 0 To newUsers.Length - 1

' get the array of selected indices from the (multiselect) list box
Dim selectedIndices As Integer() = UsersListBox.GetSelectedIndices()

' get the selectedIndex that corresponds to the counter (i)
Dim selectedIndex As Integer = selectedIndices(i)

' get the ListItem in the UserListBox Items collection at that offset
Dim myListItem As ListItem = UsersListBox.Items(selectedIndex)

' get the string that is that ListItem's value property
Dim newUser As String = myListItem.Value

' add that string to the newUsers collection of string
newUsers(i) = newUser

' Add users to the selected role

Roles.AddUsersToRole(newUsers, RolesListBox.SelectedItem.Value)

usersInRole = Roles.GetUsersInRole(RolesListBox.SelectedItem.Value)

UsersInRoleGrid.DataSource = usersInRole

End Sub

it worked as it was supposed to. But how can I check if user is already belonged to a Role ?

Thanks a lot !
3/21/2007 9:54:53 AM 27051 articles. 1 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 5


The RoleModelProvider has two functions for this:


        // Summary:
        //     Gets a value indicating whether the currently logged-on user is in the specified
        //     role.
        // Parameters:
        //   roleName:
        //     The name of the role to search in.
        // Returns:
        //     true if the currently logged-on user is in the specified role; otherwise,
        //     false.
        // Exceptions:
        //   System.Configuration.Provider.ProviderException:
        //     Role management is not enabled.
        //   System.ArgumentNullException:
        //     roleName is null.-or-There is no current logged-on user.
        //   System.ArgumentException:
        //     roleName is an empty string or contains a comma (,).
        Roles.IsUserInRole(string roleName);
        // Summary:
        //     Gets a value indicating whether the specified user is in the specified role.
        // Parameters:
        //   username:
        //     The name of the user to search for.
        //   roleName:
        //     The name of the role to search in.
        // Returns:
        //     true if the specified user is in the specified role; otherwise, false.
        // Exceptions:
        //   System.ArgumentNullException:
        //     roleName is null.-or-username is null.
        //   System.Configuration.Provider.ProviderException:
        //     Role management is not enabled.
        //   System.ArgumentException:
        //     roleName is an empty string or contains a comma (,).-or-username contains
        //     a comma (,).
        Roles.IsUserInRole(userName, roleName)
Matthias :)
3/21/2007 2:15:22 PM has following two methods: 

RoleProvider.GetUsersInRole Method

RoleProvider.IsUserInRole Method

Zhao Ji Ma
Microsoft Online Community Support

“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
3/26/2007 9:24:46 AM

Similar Artilces:

Creating User Account Without Default Security Role (Registered User Role)
  My DNN version is 3.1.1. The portal is set to Private Registration. Unauthenicated users have access to the basic pages of the site. We require my company's current customers to register and be approved to have access to all other pages that contain information restricted to them (the major part of the site). As you know, authorizing a user account applys the Registered User security role by default and this is how I control access to the customer areas.  We want to create a page that will be used by Marketing to allow potential customers by login to...

Check if User already belonged to a Role (Problem)
HelloI'm having a problem with checking if a user already has a Role before assigning a Role to them. Here is my partical code.' Check if a User belonged to a Role If (User.IsInRole(newUsers.ToString)) Then Msg.Text = " User already has a Role " Exit Sub Else ' Add users to the selected role Roles.AddUsersToRole(newUsers, RolesListBox.SelectedItem.Value) End IfBut it's not working at all. Everytime, I tried to assign a user who has a role aready, it gave me error instead of showing the text User already has a Role. I've got err...

Manage Users For This Role / Manage Roles For This User Question
In the roles/user management pages there is a link called Manage Users For This Role and Manage Roles For This User respectively. I want non Admins to be able to see these pages, and currently I have it so that they can see the manage users and manage roles pages. However, when a non admin clicks on Manage Users For This Role or Manage Roles For This User link it does not display the control, just an empty page. I can get around this by giving edit rights to the page, but I do not want them to have edit rights for the page. Any ideas? Thanks  ...

problem redirecting user based on user role
Hi all, I have small problem redirecting  user based on user role how can i determine if  a user belong to a specific group of users then  redirect  to specific page to allow access to user on user role i'm using membership and bulit in aspnet data base generated by  ASP.NET configuartion tool heres a  fragment of what i'm trying to fulfill thanks in advance of your helpprotected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {if (Membership.ValidateUser(Login1.UserName, Login1.Password)) {FormsAuthentication.SetAuthCookie(Login1...

Getting list of all users in Superuser role
Hello, I need a way to return a list of all the UserID's for the Superuser role. I tried using GetUsersInRole but it looks like this function is only for "regular" roles. For example : Public Function GetUserIDsInSuperuserRole(ByRef PortalID As Integer) As ArrayList     Dim arrUsers As New ArrayList     Dim objRoles As New DotNetNuke.Security.Roles.RoleController     For Each objUser As DotNetNuke.Entities.Users.UserRoleInfo In objRoles.GetUsersInRole(PortalID, glbRoleSuperUser)         arrUsers.Add(objUse...

Get list of users assigned to a specific role
I have a role called Contractor...  In code, I need to get the list of all users assigned to this role for display in a Drop Down List...  Can someone provide me a sample set of code for doing this using DNN objects...  Thanks...  This should get you started. You can then bind to a ddl or an array. Just replace the RoleId with that of the Contractor roleid. Dim objUser As new UserController objUser.GetRoleMembership(PortalId, RoleId, UserId)...

Login controls
HiI'm building a web app in visual studio 2005 and I'm setting up a 'create user' page for the admin part of the app. I'm creating a customised CreateUserWizard so that I can add a user to the membership list (in database on my server) and also add some info to one of my tables (user first name, faculty they work for etc).  I want to be able to let the admin user allocate roles (those already defined in my config) from a drop down list. I want to inculde this in my create user wizard, and have an 'update user' section where I can change their role the...

Problem with FreeTextBox on a Module with similar functionality to Editing Users and User Roles
  Hi,   I'm trying to design a module and I'm getting an error message when I open the page.  The error message is:-   Error: A Runtime error has occured. Do you wish to debug? Line: 39 Error: Expected ';'   The issue I have is:-   I have a normal module page that is displaying a list of clients.   I can then edit the clients details by moving to the edit page.   On the edit page, I can further edit some details of the client.  At the bottom of the page, I have an edit button, and it runs this code:-   Response.Redirect(Navig...

Problem Adding users to Selected Role
Hey all, Below is my aspx.vb code and I am stumped as to why when I enter a user name then select a role the user is added to a role, but not the one I select in my dropdown. The user is always added to the first role in the list in the dropdown not the role I selected. As well the RemoveUserFromRole doesn't work, I have to go into my DB and remove them manually. Imports System.Web.Security Partial Class AddRemoveUserRoles Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load DataBind() End Sub Pub...

Membership and Role Management
Hello, I've configured SQL server 2005 as my back-end data store via aspnet_regsql.exe. I presume it was succesvol. Creating users en roles programmatically is no problem. When I start the Web Site Administration Tool I can see the created users and roles. But when I want to show them by code I get an empty result. ... ... Roles.GetAllRoles()...... membership.GetAllUsers() The roleManager is enabled in web.config.<roleManager defaultProvider="SqlProvider" enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" cookieTimeout="30" cookiePath="/" cookieRequireSS...

Roles, roles, roles
Hey is it posible o have a role for a user to only update the content? I don't want that user to change skins or to make other admin changes... up I think if you allow a role to edit contents on a module level he wont be able to change anything else. Did you try that? cheers, erikErik van Ballegoij, The Netherlands if you allow a role to edit contents in a module lets say discussions module, then that role will be able to edit, delete the threads. so for a role to be able to add new thread only, do we need to write our own code?-keeara g------------------ keeara, see...

I'm using a CreateUserwizard control and in the code behind for CreatedUser event I am trying to add the following single line of code:  Roles.AddUserToRole ... etc. However, Intellisense does not show Roles. (I am seeing RoleServiceManager but not Roles) Any idea why? I have Visual Studio 2008 and the project is targeting .NET Framework V3.5. Also, I have <roleManager enabled="true"> in the web.config file. Intellisence will work automatically, There is no relation to web.config, if any problem use,using System.Web.Security; ...

Manage users and roles for users
Hi. I want to know how can i manage my users and users roles on my hosted website. I want that admin controls (when i log in as admin) allow me to change users roles and other stuff. Any1 have any guide or know any website that teach how to create a "admin.aspx" page to manage users and roles? thx Do you have the schema ready ? If yes, are you willing to change the schema ? Are you using ASP.NET 2.0 ? If yes, you can easily do this using the administration tool in ASP.NET 2.0.                 &n...

beginner's question - sitemaps and roles
This might be a beginner's question but I can't find any examples.  I have a sitemap with roles.  I have existing custom login code.  I know the users role from the database once they log in.  How do I let the sitemap know this user is a particular role?  Is there a property to set?   I have added the "securityTrimmingEnabled" to the web.config.  All the examples I find are using the 2.0 security that is built in. sample sitemap: <?xml version="1.0" encoding="utf-8" ?> <siteMap xmlns="

Web resources about - Problem : Get a list of user belonged to a role or to know if a user already has a role -

Powerball Winning Ticket: Who Won The $1.6 Billion Jackpot? Crowds Swarm Chino Hills 7-11 Where Ticket ...
The winning Powerball ticket has been sold, and a lucky winner from Chino Hills is now $1.6 billion richer. After Wednesday’s winning Powerball ...

Apple might lose its encryption battle in New York
While Apple is still fighting any nationwide attempt to have backdoors installed in otherwise secure devices and Internet services, it might ...

Full Episode: WN 01/13/16: Iran Releases Navy Sailors
Surprising Republican response to State of the Union; Powerball jackpot tips if you win.

Is Google Maps’ Secret Driving Mode ‘Google Here’ Without The Ads?
Mobile users who have relied on Google Maps in the past have sometimes reported issues that have incorrectly led them to the wrong destinations, ...

Co-Star Of David Bowie’s 1983 Song ‘China Girl’ Recalls Her Time With The Late Star: ‘He Was Beautiful’ ...
Amid the voluminous tributes and reminiscences regarding recently departed rock icon David Bowie, few are more candid and touching than the fond ...

Pewdiepie gathers online video stars for entertainment network
YouTube star Pewdiepie wouldn't earn millions from the video platform if he weren't tremendously popular, so creating a network of his own sounds ...

Adios Al Jazeera America. The network closes its door.
In some ways I’m actually surprised that it took three years, but Al Jazeera America is shutting down. The Washington Post has the top line , ...

Kate del Castillo Breaks Silence About El Chapo Interview
Kate del Castillo, the Mexican actress who helped arrange Sean Penn’s Rolling Stone interview with Joaquín “El Chapo” Guzmán, took to social ...

Arsonist set fire to a Scottish mosque days after the ISIS attacks in Paris
The video footage, which lasts almost four minutes, shows an as yet unidentified man pouring flammable liquid all over the floor of Bishopbriggs, ...

Virtual and Augmented Reality May be a ‘Game Changer’ Like PCs, Says Goldman
Goldman Sachs ’s Heather Bellini and team today offered up a 58-page think piece on the future of virtual reality and augmented reality , the ...

Resources last updated: 1/14/2016 7:00:10 AM