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.
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); } } } }); }
}
0 comments:
Post a Comment