How to add custom list from event receiver of feature activation dynamically and how to add spfieldtype.Text, spfieldtype.number, spfieldtype.number dropdown select range limit in sharepoint sp
2010:
The below sample code demonstrate how to add choice / dropdown value property for a particular column using event receiver of feature avtivation in sharepoint 2010.
This sample
ADD SPFieldType.Choice, SPFieldChoice with SPChoiceFormatType.RadioButtons
Code:
using Microsoft.SharePoint;
using System.Collections.Specialized;
public void OnActivated(SPFeatureReceiverProperties properties)
{
SPWeb web = (SPWeb)properties.Feature.Parent;
string url = new Uri(web.Url).AbsolutePath;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.GetListFromUrl("Shared Documents/Forms/AllItems.aspx");
StringCollection categories = new StringCollection();
categories.AddRange(new string [] {"Choice A", "Choice B", "Choice C"} );
docLib.Fields.Add("MyNewField", SPFieldType.Choice, true, false, categories);
SPFieldChoice fieldChoice = (SPFieldChoice)docLib.Fields["MyNewField"];
fieldChoice.DefaultValue = "Choice A";
fieldChoice.EditFormat = SPChoiceFormatType.RadioButtons;
fieldChoice.Update();
docLib.Update();
OR
SPListCollection lists = web.Lists;
SPList listitem = web.Lists.TryGetList("Listname");
if(listitem == null)
{
lists.Add("Listname","Your comments here", SPListTemplateType.GenericList);
SPList newitem = web.Lists["Listname"];
newitem.Fields.Add("Name",SPFieldType.Text, true); // for adding text, true- indicateds this column is mandatory
newitem.Fields.Add("Link",SPFieldType.URL, true); // for adding URL, true- indicateds this column is mandatory
newitem.Fields.Add("ItemCount",SPFieldType.Number, true); // for adding number, true- indicateds this column is mandatory
StringCollection categories = new StringCollection(); // for adding choice dropdown, true- indicateds this column is mandatory
categories.AddRange(new string [] {"Choice A", "Choice B", "Choice C"} );
newitem.Fields.Add("Range", SPFieldType.Choice, true, false, categories);
newitem.OnQuickLaunch = true;
newitem.update();
// to display item on default load
SPView itemview = newFeatureList.DefaultView;
itemview.ViewFields.Add("Name");
itemview.ViewFields.Add("Link");
itemview.ViewFields.Add("ItemCount");
itemview.ViewFields.Add("Range");
itemview.update();
}
}
No comments:
Post a Comment