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 Custom hit counter in SharePoint2010 using Sandbox Solution

In this blog I am going to demonstrate how to create Hit counter for SharePoint site with user details using sandbox solution. I took reference from codeplex code(http://hitcounter.codeplex.com) which is sharepoint2007. I modified his sample and tried make it simple and easy for you. Once you understand the way I created then its very simple for you to make any further modification depends on your requirement.
This solution will be very useful when you need detail about the person who visit this page and also about the number of time page view with page detail. I created this solution that will make your work easy. It's very simple where you don't need to do anything except deploying the feature and adding the web part into you master page or layout page in sharepoint2010.
Below is the screenshot that will display the how it looks like:

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
publicclassCustomWebPart : WebPart
03
{
04
protectedoverridevoidCreateChildControls()
05
{
06
LiteralControl lt = newLiteralControl();
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 (Site Action->View All Pages->Pages).

We can see the code is working fine. The next step…

Step by step BCS in SharePoint2010

Hi friends,
Through this blog I am going to share the e-Book on BCS in Sharepoint2010 which guide you in development for Business Connectivity Service in sharepoint2010.This books contains everything about BCS  with screens and real scenerio examples. Vijai Anand (Author of this e-book) have covered all possibles scenerio which required for BCS.

Below are the Contents in this e-book:

1 Business data connectivity services: an overview

2 Configure business data connectivity services
3 Configure BCS service application association