Vanou’s Blog

Posts Tagged ‘MOSS 2007

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

        }

      });

    }