Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint

SharePoint 2010 Groups and Users

5.00/5 (2 votes)
17 Dec 2012CPOL1 min read 28.5K   189  
The server object model for fetching groups and users.

Introduction

In this article we can explore the Server Object Model for dealing with Groups and Users inside SharePoint.

Our Aim

Our aim is to create a webpart that displays the users and groups in a SharePoint site.

For example:

Group 1

  • User 1
  • User 2

Group 2

  • User 3
  • User 4

The Solution

Create a new SharePoint solution and add a new webpart into it. Place a Literal control over it.

Image 1

Add using System.Text; 

In the Page Load event, add the following code: 

C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.Page.IsPostBack)
        RefreshData();
}

private void RefreshData()
{
    StringBuilder sb = new StringBuilder("<h2>Groups & Users</h2></br>");

    foreach (SPGroup group in SPContext.Current.Web.Groups)
    {
        sb.Append("<b>Group: </b>" + group.Name + "</br>");
        foreach (SPUser user in group.Users)
        {
            sb.Append(user.Name + "</br>");
        }

        sb.Append("</br>");
    }

    Literal1.Text = sb.ToString();
}

What the Code Does

SPContext.Current.Web.Groups returns all the groups for the particular web object. We can enumerate this using a foreach statement.

Group.Users returns the users inside the particular group. The object is represented by the SPUser object model.

Running the Code

On running the project, and adding the web part to the page, you can see the following results:

Image 2

More Information on Groups and Users

I would like to add some related information from MSDN.

SPWeb.AllUsers

Gets the collection of user objects that represents all users who are either members of the site or who have browsed to the site as authenticated members of a domain group in the site.

SPWeb.Users

Gets the collection of user objects that are explicitly assigned permissions in the Web site.

Summary

In this article we have explored the server object model for fetching groups and users. The web part displaying groups and users is attached with the article.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)