Search This Blog

Wednesday, February 18, 2015

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

No comments:

Post a Comment