65.9K
CodeProject is changing. Read more.
Home

Get value collection of a SharePoint Choice Field

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 23, 2011

CPOL
viewsIcon

32671

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;
        }