Showing posts with label Add fields Programmatically. Show all posts
Showing posts with label Add fields Programmatically. Show all posts

Tuesday, June 19, 2012

Create SharePoint Lookup Field Programmatically


Lets see how to create a lookup field in a list programmatically

Lets you have a list named "Expense" and another list "Expense Category"

In the "Expense" list you want a lookup field from "Expense Category" list on "Expense Category" field

First add a lookup field named "Category" in the "Expense" list as

   SPList Expense = web.Lists.TryGetList("Expense");
   SPList ExpenseCategory = web.Lists.TryGetList("Expense Category");

   SPFieldCollection _fields = Expense.Fields;

   _fields.AddLookup("Category", ExpenseCategory.ID, true);

In above code i get the collection of fields from the "Expense" list and added a lookup field named "Category" and passed the

GUID of "Expense Category" list from lookup is to be set and set required to true.

Now get the recently created lookup field as

   SPFieldLookup Category = Expense.Fields["Category"] as SPFieldLookup;

Set the lookup field from the "Expense Category" list, Field "Expense Category" and update the field

   Category.LookupField = ExpenseCategory.Fields["Expense Category"].InternalName;


   Category.Update();


deploy the solution and verify the lookup field created in the list

Friday, June 15, 2012

Programmaticlly Create Choice Field with Default Value in SharePoint


In this post i am explaining how to create a choice field in the list and set its default value pro-grammatically

First create a string collection of choice values that you want to use

  StringCollection _statusTypes = new StringCollection();
            _statusTypes.Add("Complete");
            _statusTypes.Add("Incomplete");

Get the field collection from the list and add new choice field to this


 SPList list = web.Lists[listname];
            SPFieldCollection _fields = list.Fields;


  _fields.Add("MyChoiceField", SPFieldType.Choice, true, false, _statusTypes);

Here "MyChoiceField" is the name of field with _statusTypes choice values.

Next to set the default value of the choice field use the code below

Get the choice field
        SPFieldChoice fieldChoice = (SPFieldChoice)list.Fields["MyChoiceField"];
Set its default value              
      fieldChoice.DefaultValue = "Incomplete";
Set the format dropdown or radio button            
      fieldChoice.EditFormat = SPChoiceFormatType.RadioButtons;
and update the field
      fieldChoice.Update();
Now deploy the solution and add new item in the list you will see the default value set for this choice field