Return/Update values of an SPFieldChoice object
Posted May 14, 2009
on:
/// <summary>
/// Returns a StringCollection object from a SPField object of type SPFieldChoice from the web.Fields
/// </summary>
/// <param name=”fieldName”>Field name needed to retrieve the list of choice of the SPFieldChoice object</param>
/// <returns></returns>
public static StringCollection GetAllFieldChoices(string fieldName)
{
StringCollection fieldChoices = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb origWeb = SPContext.Current.Web;
while (!origWeb.IsRootWeb)
origWeb = origWeb.ParentWeb;
try
{
using (SPSite site = new SPSite(origWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPField field = web.Fields[fieldName] as SPField;
if (field != null)
{
if (field.Type == SPFieldType.Choice)
fieldChoices = ((SPFieldChoice)field).Choices;
}
}
}
}
catch (Exception ex)
{
throw;
}
});
return fieldChoices;
}
/// <summary>
/// Update an SPFieldChoice Field of the SPWeb
/// </summary>
/// <param
name=”fieldName”>Name of the
field</param>
/// <param
name=”choices”>StringCollection
that represents the choices for the field</param>
public static void
UpdateSPFieldChoice(string fieldName,
System.Collections.Specialized.StringCollection
choices)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb
origWeb = SPContext.Current.Web;
while
(!origWeb.IsRootWeb)
origWeb = origWeb.ParentWeb;
try
{
using
(SPSite site = new
SPSite(origWeb.Url))
{
using
(SPWeb web = site.OpenWeb())
{
SPField
field = web.Fields[fieldName] as SPField;
if
(field != null)
{
if
(field.Type == SPFieldType.Choice)
{
int
numberOfChoices = choices.Count;
string[]
values = new String[numberOfChoices];
choices.CopyTo(values, 0);
web.AllowUnsafeUpdates = true;
SPFieldChoice
spFied = field as SPFieldChoice;
if
(spFied != null)
{
spFied.Choices.Clear();
spFied.Choices.AddRange(values);
spFied.Update();
}
}
}
}
}
}
catch (Exception ex)
{
throw;
}
});
}
1 | Sasi Kumar Reddy
November 30, 2012 at 9:18 am
Best way to add choice field data to the dropdownlist with required validation
http://sharepointquicksolutions.blogspot.in/2012/11/spfieldchoice-to-dropdown-list.html