"The day you stop learning SharePoint is the day you stop using it."

Showing posts with label SP Object Model. Show all posts
Showing posts with label SP Object Model. Show all posts

Easiest way to populate a drop-down list control with SharePoint custom list column values

There are numerous ways to populate a drop-down list control with SharePoint custom list column values. But for me the below seems to be the easiest one.

You should populate the drop-down list on a page load event as given in below code. You can copy the exact below code with few changes as what column values you want to populate and your drop-down list control ID/Name.


I have used here 
SPQuery since I want to order the column values alphabetically, starting from ascending to descending. You can omit the SPQuery statement and directly specify the column value in spList.GetItems() method.

Example: SPListItemCollection spListColl = spList.GetItems("Title"); // Title is the column name. You can mention any column name of your choice.

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      Guid spSiteGUID = SPContext.Current.Site.ID;
      Guid spWebGUID = SPContext.Current.Site.RootWeb.ID;

      //Use above statement if your site is at root site or else below one.  
      //Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID; 

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
         using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
         {
            using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
            {
               SPList spList = elevatedWeb.Lists["QD Offices"];
               SPQuery spQuery = new SPQuery();
               spQuery.Query = "<OrderBy><FieldRef Name='Country'/></OrderBy>";
               SPListItemCollection spListColl = spList.GetItems(spQuery);
               foreach (SPListItem spItem in spListColl)
               {
                  string listItem = spItem["Title"].ToString();
                  ddl_location.Items.Add(listItem);
               }
            }
         }
      });
   }
}


Cheers !!
Share:

SharePoint-StackExchange Moderator

Author's Profile

My photo
India
A SharePoint Enthusiast working as a Lead Solution Architect for an IT Software & Consulting Company in Mumbai. I believe in giving back to the community through which I also learn and develop and eventually grow as an individual and professional. This blog is a small contribution to the community where I live in and may help someone who is seeking knowledge like me.

Popular Posts

Powered by Blogger.

Contact Form

Name

Email *

Message *

Total Pageviews