Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / productivity / SharePoint

Get value collection of a SharePoint Choice Field

5.00/5 (1 vote)
24 Jun 2011CPOL 32.7K  
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)