Binding Users Details To DropDownList In SharePoint 2013 Using C#

Overview:

The following post will help you in binding the SharePoint people field names to DropDownList using C# code.

List Details:


Code:

  1. using System;  
  2. using System.Web.UI;  
  3. using System.Web.UI.WebControls;  
  4. using System.Web.UI.WebControls.WebParts;  
  5. using Microsoft.SharePoint;  
  6. using System.Collections.Specialized;  
  7. using System.Data;  
  8. using System.Collections;  
  9. using System.Text;  
  10. namespace RK_Solution.VisualWebPart1  
  11. {  
  12.     public partial class VisualWebPart1UserControl: UserControl  
  13.     {  
  14.         protected void Page_Load(object sender, EventArgs e)  
  15.         {  
  16.             SPSite site = SPContext.Current.Site  
  17.   
  18.             using(SPWeb web = site.OpenWeb())  
  19.             {  
  20.                 SPList issueRepList = web.Lists["Issue Representative"];  
  21.             SPListItemCollection issueRepItems = issueRepList.Items;  
  22.                 DataTable dtUsers = new DataTable();  
  23.                 dtUsers.Columns.Add("User"typeof(string));  
  24.                 foreach(SPListItem item in issueRepItems)  
  25.                 {  
  26.                     if (item["IssueRepId"].ToString() == "5")  
  27.                     {  
  28.                         SPFieldUserValueCollection userCol = new SPFieldUserValueCollection  
  29.                         (SPContext.Current.Web, item["Representatives"].ToString());  
  30.                         foreach(SPFieldUserValue usrItm in userCol)  
  31.                         {  
  32.                         string temp = usrItm.User.Name.ToString();  
  33.                             dtUsers.Rows.Add(temp);  
  34.                         }  
  35.                         ddlIssueRep2.DataSource = dtUsers;  
  36.                         ddlIssueRep2.DataTextField = "User";  
  37.                         ddlIssueRep2.DataValueField = "User";  
  38.                         ddlIssueRep2.DataBind();  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.     }  
  44. }   

Output:


Ebook Download
View all
Learn
View all