3

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;

2 Answers 2

2

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

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/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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