Skip to main content

Display SharePoint Users, Groups and Sites in a GridView and Use a DropDownList to filter the values

This article will explain how to display SharePoint Users, Groups and Sites in a Gridview and use a DropDownList to filter the values.
Step 1: Open the Visual Studio and create a new project; select visual webpart (I am giving an example using a visual webpart).
Step 2: Add the GridView to your user control, e.g.
<asp:GridView ID="gvLists" runat="server" AutoGenerateColumns="False"
CellPadding="4" EnableModelValidation="True" ForeColor="#333333"
GridLines="None" OnRowCommand="gvLists_RowCommand">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chk_Selected" runat="server" Style="position: static" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Country" HeaderText="Country" />
<asp:BoundField DataField="UserName" HeaderText="Role" />
<asp:BoundField DataField="Role" HeaderText="User Name" />
<asp:CommandField HeaderText="Select" ShowHeader="True" ShowSelectButton="True" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
Step 3: Code behind for the GridView will look like below:
protected void Page_Load(object sender, EventArgs e)
{

try
            {
DataTable dtLists = new DataTable();
                dtLists.Columns.Add("Country");
                dtLists.Columns.Add("UserName");
                dtLists.Columns.Add("Role");

//Get all users by site position and group.
SPSite spSite = new SPSite(SPContext.Current.Site.Url);
foreach (SPWeb web = spSite.AllWebs)
                {
foreach (SPGroup group in web.Groups;)
                        {
foreach (SPUser user in group.Users)
                            {
DataRow dr = dtLists.NewRow();
                                dr["Country"] = web.Title;
                                dr["Role"] = group.Name;
                                dr["User"] = user.LoginName;
                                dtLists.Rows.Add(dr);
                            }
                        }
                    }
                }
                gvLists.DataSource = dtLists;
                gvLists.DataBind();
            }
catch (Exception ex)
            {
throw ex;
            }

}
Step 4: Output

Share1.gif
Step 5: Next, add a Dropdown to filter data just above the GridView like this:
<table>
<tr>
<td>
  User :
</td>
<td class="style1">
<asp:DropDownList ID="filterUser" AutoPostBack="true" runat="server" EnableViewState="true"
onselectedindexchanged="filterUser_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
  Country :
</td>
<td >
<asp:DropDownList ID="filterCountry" AutoPostBack="true" runat="server" EnableViewState="true"
onselectedindexchanged="filterCountry_SelectedIndexChanged"></asp:DropDownList>
</td>
</tr>
<tr>
<td>
  Role :
</td>
<td >
<asp:DropDownList ID="filterRole" AutoPostBack="true" runat="server" EnableViewState="true"
onselectedindexchanged="filterRole_SelectedIndexChanged">
<asp:ListItem Text="--All Roles--" Value="All" Selected="True"></asp:ListItem>
<asp:ListItem Text="Super Administrator" Value="Super Administrator"></asp:ListItem>
<asp:ListItem Text="Regional Administrator" Value="Regional Administrator"></asp:ListItem>
<asp:ListItem Text="Marketing Administrator" Value="Marketing Administrator"></asp:ListItem>
<asp:ListItem Text="Country Administrator" Value="Country Administrator"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
Step 6: Add the code behind for filters:
//call this method in page load to load the value
private void bindfilters()
        {
//for country
try
            {
                filterCountry.Items.Clear();
                filterUser.Items.Clear();
SPWeb oWeb = SPControl.GetContextWeb(Context);
                oWeb.AllowUnsafeUpdates = true;
                filterCountry.Items.Insert(0, new ListItem("--All Country--", "0"));
                filterUser.Items.Insert(0, new ListItem("--All users--", "0"));
foreach (SPUser user in oWeb.AllUsers)
                {
                    filterUser.Items.Add(user.LoginName);
                }
SPSite site = SPContext.Current.Site;
SPList listname = site.RootWeb.Lists[countrySiteListName];
foreach (SPListItem item in listname.Items)
                {
                    filterCountry.Items.Add(item[countrySiteCoulumnName].ToString());
                }
            }
catch (Exception ex)
            {
throw ex
            }
        }
//Action on dropdowns
/// <summary>
/// Filtering the gridview data based on Users
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void filterUser_SelectedIndexChanged(object sender, EventArgs e)
        {
try
            {
                filterCountry.ClearSelection();//.Items.Clear();
//filterUser.Items.Clear();
                filterRole.ClearSelection();
if (filterUser.SelectedItem.Text != "--All users--")
                {
DataTable dtLists = new DataTable();
                    dtLists.Columns.Add(countrySiteCoulumnName);
                    dtLists.Columns.Add("UserName");
                    dtLists.Columns.Add("Role");
//Get all users by site position and group.
SPSite site = SPContext.Current.Site;
SPList listname = site.RootWeb.Lists[countrySiteListName];

foreach (SPWeb web in SPContext.Current.Site.AllWebs)                    {

SPGroupCollection groupcoll = web.Groups;
foreach (SPGroup group in groupcoll)
                            {
SPUser user = group.Users[filterUser.SelectedItem.Text];
DataRow dr = dtLists.NewRow();
                                    dr["Country"] = web.Title;
                                    dr["Role"] = group.Name;                                    dr["UserName "] = user.LoginName;
                                    dtLists.Rows.Add(dr);

                       }

                     }
                    gvLists.DataSource = dtLists;
                    gvLists.DataBind();
                }
else
                {
                    GetUsers();
                }
            }
catch (Exception ex)
            {
            }
        }

/// <summary>
/// Filtering the gridview data based on Country
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void filterCountry_SelectedIndexChanged(object sender, EventArgs e)
        {
try
            {
                filterUser.ClearSelection();
                filterRole.ClearSelection();

if (filterCountry.SelectedItem.Text != "All")
                {

DataTable dtLists = new DataTable();
                    dtLists.Columns.Add("Country");
                    dtLists.Columns.Add("UserName");
                    dtLists.Columns.Add("Role");

SPSite spSite = new SPSite(SPContext.Current.Site.Url);
using (SPWeb web = spSite.AllWebs[filterCountry.SelectedItem.Text])
                    {
SPGroupCollection groupcoll = web.Groups;
foreach (SPGroup group in groupcoll)
                        {
// filterRole.Items.Add(group.Name);
foreach (SPUser user in group.Users)
                            {
DataRow dr = dtLists.NewRow();
                                dr["Country"] = web.Title;
                                dr["Role"] = group.Name; //role.Name;
                                dr["UserName"] = user.LoginName;
                                dtLists.Rows.Add(dr);
                            }
                        }
                    }
                    gvLists.DataSource = dtLists;
                    gvLists.DataBind();
                }
else
                {
                    GetUsers();
                }
            }
catch (Exception ex)
            {
                            }
        }

/// <summary>
/// Filtering the gridview data based on Role
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void filterRole_SelectedIndexChanged(object sender, EventArgs e)
        {
try
            {
                filterCountry.ClearSelection();//.Items.Clear();
                filterUser.ClearSelection();
//filterRole.ClearSelection();
if (filterRole.SelectedItem.Value != "All")
                {
DataTable dtLists = new DataTable();
                    dtLists.Columns.Add("Country");
                    dtLists.Columns.Add("UserName");
                    dtLists.Columns.Add("Role");
SPSite spSite = new SPSite(SPContext.Current.Site.Url);
foreach (SPWeb web = spSite.AllWebs)
                    {
SPGroup group = web.Groups[filterRole.SelectedItem.Text];
foreach (SPUser user in group.Users)
                                {
DataRow dr = dtLists.NewRow();
                                    dr["Country"] = web.Title;
                                    dr["Role"] = group.Name; //role.Name;
                                    dr["UserName"] = user.LoginName;
                                    dtLists.Rows.Add(dr);
                                }

                    }
                    gvLists.DataSource = dtLists;
                    gvLists.DataBind();
                }
else
                {
                     //method will load gridview complete data.
                    GetUsers();
                }
            }
catch (Exception ex)
            {
                           }
        }

Step 7: Output
Share2.gif
Hope you like this article....

Comments

Popular posts from this blog

Create a Web Part Page with a Web Part in Sharepoint 2010

Source code from codeplex In this blog I am going to explain how to create a web part page along with a web part. After using this feature, we just need to activate the feature; the rest will complete automatically. Steps for creating the functionality: Step 1: Create a project with Farm-Based solution: Step 2: Add a new item as webpart: Step 3: Add feature event receiver class, your solution should look like the following: Step 4: Add your logic to the web part: 01 [ToolboxItemAttribute( false )] 02 public class CustomWebPart : WebPart 03 { 04 protected override void CreateChildControls() 05 { 06 LiteralControl lt = new LiteralControl(); 07 lt.Text = "This webpart automatically added with page" ; 08 this .Controls.Add(lt); 09 } 10 } Step 5: You need to provide logic in the feature Reciever class. Find the attached file to see the source code. Step 6: Build, deploy and activate the feature. Step 7: Go to Page library ( S

SharePoint Branding Solution Pack using VS2010

Introduction Today, in this blog I am trying to provide you the Custom Branding solution Pack. This solution pack will save time and effort while developing the custom sharepoint with publishing sites in sharepoint. It works great. So, we all are good to go and use this re-usable solution pack. Description The source code shows how to prepare a structure for Sharepoint Branding solution. This pack contains : Master Page Gallery structure Page Layout Gallery structure Image Gallery Styles Library gallery Event Receiver

How to create Sandbox solution with full trust Proxy

Download Files: CustomSBFullTrust.zip In this article I am explaining the step by step procedure to create a sandbox solution with full trust proxy. Before starting I am assuming you are aware of the sandbox limitations. Full trust solution is providing sandbox solution to work in a full environment. In short this is the way to achieve farm based solution functionality in a Sandbox. Namespace Required: using Microsoft.SharePoint.UserCode; using Microsoft.SharePoint.Security; using System.Security.Permissions; using Microsoft.SharePoint; using Microsoft.SharePoint.Publishing;