Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I have a site column of type choice that I have associated with a Site content type. I want to get the values of that choice field to use in a custom web part. Should I use the Field name, GUID or Display name? And how?

I tried this and get a not found error.

SPFieldChoice deptField = SPContext.Current.Fields[new Guid("72D34B8A-549A-43AF-BD25-9A00497EECE8")] as SPFieldChoice;
share|improve this question

2 Answers 2

up vote 2 down vote accepted

Your site column is deployed to the Site Column Gallery in a site. So first you need to get a reference to the site (i.e. an SPWeb object), then you get access to the site column using the Fields collection. Generally you pass the internal name of the site column as a parameter.

When you define the site column using CAML you set the following attributes: Name, DisplayName, and StaticName. The Name attribute is the internal name. It gets set when the site column is created and does not change over its lifetime. You could reference the site column using its ID (as you did in your question) but it makes your code unreadable.

Once you have the site column, you need to cast it as an SPFieldChoice and then you can get the choice values from the Choices property.

var web = SPContext.Current.Web;
var deptField = web.Fields["<internal name">"] as SPFieldChoice;
var values = deptField.Choices;
share|improve this answer
    
Thanks Rob, this worked perfect. –  Jason Jones Jul 12 '11 at 0:04

It looks like SPContext.Current is NOT referring to the List Item which contains the field. First get to the List/Library item and access it using Fields collection as shown here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldcollection.aspx

To Read and Write data to multichoice field value, Check follwing links:

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldmultichoicevalue.aspx

http://blog.qumsieh.ca/2008/12/27/working-with-spfieldmultichoicevalue-saving-and-loading/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.