Skip to main content

Cloud

Using LINQ to Order SharePoint List Items and Choice Site Columns within a Dropdown List

Populating dropdown lists data from choice site columns and lookup lists is a fairly common task when creating custom SharePoint web parts.A small side effect of doing this is that when the dropdown is populated, the values will often not be in alphabetical order. This is not the end of the world, so the simplest, fastest solution is the best in this case. Hence LINQ to the rescue!

To contain our LINQ sort, let’s create two helper methods for populating the dropdowns, one for choice site columns and one for lookup lists.

private void PopulateDropDownWithList(SPList list, DropDownList ddl)

{

//add blank item at the start of the drop down

ddl.Items.Add(—-Select Value—-);

 

//order list items alphabetically

var orderedListItems = from SPListItem anItem in list.Items

orderby anItem.Title

ascending select anItem;

 

//add title field in list to the drop down

foreach (SPListItem item in orderedListItems)

{

ddl.Items.Add(item.Title);

}

}

 

private void PopulateDropDownWithChoiceSiteColumn(string columnName, DropDownList ddl, SPWeb web)

{

//add blank item at the start of the drop down

ddl.Items.Add(—-Select Value—-);

SPFieldChoice column = (SPFieldChoice)web.Fields[columnName];

 

//order list items alphabetically

var orderedChoiceItems = from string aChoice in column.Choices

orderby aChoice

ascending select aChoice;

 

//order list items alphabetically

foreach (string item in orderedChoiceItems)

{

ddl.Items.Add(item);

}

}

 

Note the slight variation in the LINQ query for choice columns vs. list items above.

 

The only thing left to do is add code to the Page_Load method of the user control being embedded as a child control within your web part.Assuming that ddlCountry and ddlIndustry ASP.NET DropDownList controls exist in your user control, and that a list named “Country” and a site column named “Industry” exist at the root of your site collection, this may be completed as follows:

 

using (SPSite site = SPContext.Current.Site)

{

using (SPWeb web = site.RootWeb)

{

//Populate with lists

PopulateDropDownWithList(web.Lists[Country], ddlCountry);

 

//Populate with columns

PopulateDropDownWithChoiceSiteColumn(Industry, ddlIndustry, web);

}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PBCfnezrick

More from this Author

Follow Us