Click here to Skip to main content
15,879,474 members
Articles / Productivity Apps and Services / Sharepoint
Tip/Trick

Get value collection of a SharePoint Choice Field

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
24 Jun 2011CPOL 32.3K  
How to read choice values for Multi choice questions in a Survey
Multi choice questions are very common in surveys. SpFieldChoice object can be used to access choice values programmatically.
SpFieldChoice provides a string collection which stores the choice values for multi choice field type.

Following is the code:
public static List<string> GetChoiceFieldValues
(string listName,string fieldName, string siteCollection, string webSite)
        {
            List<string> fieldList;

            SPSite spSite = null;
            SPWeb spWeb = null;

            try
            {
                if (siteCollection != null)
                    spSite = new SPSite(siteCollection);
                else
                    spSite = SPContext.Current.Site;

                if (webSite != null)
                    spWeb = spSite.OpenWeb(webSite);
                else
                    spWeb = spSite.OpenWeb();

                SPList spList = spWeb.Lists[listName];

                SPFieldChoice field = (SPFieldChoice)spList.Fields[fieldName];

                fieldList = new List<string>();

                foreach (string str in field.Choices)
                {
                    fieldList.Add(str);
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                throw;
            }
            finally
            {
                if(spWeb != null)
                    spWeb.Close();

                if(spSite != null)
                    spSite.Close();
            }

            return fieldList;
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --