User Tools

Site Tools


notes:sharepoint2010:lists_and_libraries

Lists and Libraries in SharePoint

Lists and Libraries

Obtain a list by title:

// 'web' is of type SPWeb
SPList list = web.Lists.TryGetList(listTitle);
if (list != null)
{
    // ... list exists
}

Obtain a list by ID:

SPList list = web.GetList(listId, false);

Obtain a library by libUrlName. An exception is thrown if the library does not exists:

try
{
    // Use the GetList method rather than TryGetList because libUrlName is a URL, not Title.
    SPDocumentLibrary lib = web.GetList(libUrlName) as SPDocumentLibrary;
}
catch(Exception exc)
{
    // Possible exception messages:
    // exc.Message == "Value does not fall within the expected range."
    // exc.Message == "<nativehr>0x80070002</nativehr><nativestack></nativestack>"
    // exc.Message.StartsWith("The system cannot find the file specified")
    // exc.InnerException.Message.StartsWith("The system cannot find the file specified")
}

Obtain a library by ID:

// 'web' is an SPWeb.
// 'listId' is the library's GUID.
SPDocumentLibrary lib = web.Lists.GetList(listId, true) as SPDocumentLibrary;

List Items

Create a list item:

// the 'list' variable is of type SPList
SPListItem item = list.Items.Add();
item["FirstName"] = "Leon";
item["LastName"] = "Klop";
item["Date/Time"] = DateTime.Now;
item.Update();

Obtain an SPListItem by URL:

SPListItem item = SPContext.Current.Site.RootWeb.GetListItem(itemUrl);

Obtain an SPListItem by ID:

// 'lib' is an SPDocumentLibrary. It could be also an SPList.
SPListItem item = lib.GetItemById(itemId);

Obtain a specific list item:

// Get the list. Here we obtain the list from the default website of the site collection.
SPList list = SPContext.Current.Web.Site.RootWeb.Lists["MyList"];
 
// Get the first list item that has the name of the current website in its 'SiteName' column.
var item = (from SPListItem item in myList.Items
            where (string)item["SiteName"] == SPContext.Current.Web.Name
            select item).FirstOrDefault();

A method to obtain the title of a list item:

private string GetItemTitle(SPList list, int itemId)
{
    // Check if the list item exists.
    var listEnumeration = list.Items.OfType<SPListItem>();
    var item = listEnumeration.FirstOrDefault(p => p.ID == itemId);
 
    // Return the title of the list item.
    if (item == null)
    {
        return "Item Deleted (ID=" + itemId.ToString() + ")";
    }
    else
    {
        return ((SPListItem)item).Title;
    }
}

Obtain the version of a list item:

SPListItemVersionCollection vers = listItem.Versions;
if (vers.Count >= 1)
    string version = vers[0].VersionLabel;

Update field values:

// Obtain a ListItem by URL.
SPListItem item = web.GetListItem(itemUrl);
if (item != null)
{
    // Populate fields.
    item["Field Display Name 1"] = val1;
    item["Field Display Name 2"] = val2;
    item["Field Display Name 3"] = val3;
    // ...
 
    item.Update();
}

Copy an item and set its content type:

// 'item' is an instance of SPItem
item.CopyTo(fullUrl); // fullUrl = web.Site.Url + web.Name + libUrlName + folderUrlName + fileName
 
// Obtain the newly created item.
SPListItem newItem = web.GetListItem(itemUrl); // itemUrl = web.Name + libUrlName + folderUrlName + fileName
 
// Set the content type of the new item.
SPContentType ct = web.ContentTypes[contentTypeName];
newItem["ContentTypeId"] = ct.Id;
newItem.UnlinkFromCopySource();
newItem.Update();

Copy metadata from an SPListItem to another SPListItem:

// 'item' is a source SPListItem.
// 'newItem' is another SPListItem.
foreach (DictionaryEntry entry in item.Properties)
{
    string key = (entry.Key == null ? "" : entry.Key.ToString()).ToLower();
 
    // Skip any keys you don't want to copy.
    if (!(key.StartsWith("vti_") ||
          key.StartsWith("templateurl") ||
          key.StartsWith("contenttype") ||
          key.StartsWith("xd_")))
    {
        // Try to find the key in newItem.
        DictionaryEntry? prop = null;
        foreach (DictionaryEntry p in newItem.Properties)
        {
            if (p.Key != null && p.Key.ToString().ToLower() == key)
            {
                prop = p;
                break;
            }
        }
 
        if (prop.HasValue)
        {
            // If found, assign the value from entry.Value
            if (entry.Value == null || entry.Value.ToString().Trim() == String.Empty)
                newItem[prop.Value.Key.ToString()] = null;
            else
                newItem[prop.Value.Key.ToString()] = entry.Value;
        }
    }
}
 
// Save changes to the new item.
newItem.Update();

Write a string into a file associated with an SPListItem:

// 'str' is the string to write to the file.
// 'item' is an SPListItem.
Stream outStream = new MemoryStream();
byte[] outBuffer = Encoding.ASCII.GetBytes(str);
outStream.Write(outBuffer, 0, outBuffer.Length);
 
item.File.SaveBinary(outStream);
item.File.Update();

List and Web Fields

Add a text field to a list and show it in the views:

// 'list' is of type SPList.
list.Fields.Add("NewField", SPFieldType.Text, false, false, null);
SPField field = list.Fields["NewField"];
field.ShowInEditForm = true;
field.ShowInNewForm = false;
field.ShowInDisplayForm = true;
field.ShowInViewForms = true;
field.Title = "My New Field";
field.Required = false;
field.Update();
 
list.Update();

Add fields to the default view of a list:

// 'list' is of type SPList
SPView view = list.DefaultView;
view.ViewFields.Add("IsHidden");
view.ViewFields.Add("ListUrl");
view.Update();

A method that adds a text field to a web:

private SPField AddTextField(SPWeb web, string fieldName, bool isRequired)
{
    web.Fields.Add(fieldName, SPFieldType.Text, isRequired, false, null);
    SPField field = web.Fields[fieldName];
 
    field.ShowInEditForm = false;
    field.ShowInNewForm = false;
    field.ShowInDisplayForm = true;
    field.ShowInViewForms = true;
    field.Title = fieldName;
    field.Required = isRequired;
    field.Group = "Custom Columns";
    field.Update();
 
    return field;
}

Add a choice field to a library 'lib':

var choices = new StringCollection();
choices.Add("One");
choices.Add("Two");
choices.Add("Three");
 
lib.Fields.Add("New Field", SPFieldType.Choice, true, false, choices);

Add a lookup field:

// "New Lookup Field" is a display name of the lookup field
// "FieldName" is a display name of the field referenced by the lookup field
// web is an SPWeb
// list is an SPList
web.Fields.AddLookup("New Lookup Field", list.ID, true);
SPFieldLookup lookField = (SPFieldLookup)web.Fields["New Lookup Field"];
 
lookField.LookupField = "FieldName";
lookField.Title = "New Lookup Field";
lookField.Group = "Custom Fields";
lookField.ShowInDisplayForm = true;
lookField.ShowInViewForms = true;
lookField.Update();

Check if a field exists in an SPList 'list':

// Example #1
SPField field = list.Fields.GetField("MyFieldname") as SPField;
 
// Example #2
SPField field = list.Fields.TryGetFieldByStaticName("MyFieldStaticName") as SPField;
if (field == null)
{
    // ... the field does not exist
}

Check if a Boolean field exists in a Web. Create it if it does not exist:

// 'web' is of type SPWeb
SPFieldBoolean field = (SPFieldBoolean)web.Fields.TryGetFieldByStaticName("IsHidden");
if (field == null)
{
    string fieldName = web.Fields.Add("IsHidden", SPFieldType.Boolean, false, false, null);
    field = (SPFieldBoolean)web.Fields.GetFieldByInternalName(fieldName);
 
    // Set properties
    field.Title = "Hidden";
    field.Group = "Utility Lists";
    field.Required = false;
    field.ShowInEditForm = true;
    field.ShowInNewForm = false;
    field.ShowInDisplayForm = true;
    field.ShowInViewForms = true;
 
    field.Update();
}

Obtain the internal name of a field:

string internalName = list.Fields["MyFieldName"].InternalName;

Check the type of a field 'MyFieldname' in a list 'list':

if (list.Fields.ContainsField("MyFieldname"))
{
    SPField field = list.Fields.GetField("MyFieldname");
    if (field is SPFieldText || field is SPFieldMultiLineText)
    {
        // ...
    }
    else if (field is SPFieldUser)
    {
        // ...
    }
}

Examples of adding fields of various types to a list:

// Text field
list.Fields.Add("Field1", SPFieldType.Text, false, false, null);
SPField field1 = list.Fields["Field1"];
DisplayField(field1, true);
field1.Title = "Field 1";
((SPFieldText)field1).MaxLength = 50;
field1.Required = true;
field1.Update();
 
// Number field
list.Fields.Add("Field2", SPFieldType.Number, false, false, null);
SPField field2 = list.Fields["Field2"];
DisplayField(field2, false);
field2.Title = "Field 2";
field2.Required = true;
field2.Update();
 
// Number with a format
list.Fields.Add("Field3", SPFieldType.Number, false, false, null);
SPField field3 = list.Fields["Field3"];
DisplayField(field3, true);
field3.Title = "Field 3";
((SPFieldNumber)field3).DisplayFormat = SPNumberFormatTypes.TwoDecimals;
field3.Required = true;
field3.Update();
 
// DateTime field
list.Fields.Add("Field4", SPFieldType.DateTime, false, false, null);
SPField field4 = list.Fields["Field4"];
DisplayField(field4, true);
field4.Title = "Field 4";
field4.DisplaySize = "20";
field4.Required = true;
field4.Update();
 
// Boolean field
list.Fields.Add("Field5", SPFieldType.Boolean, false, false, null);
SPField field5 = list.Fields["Field5"];
field5.Title = "Field 5";
field5.Update();
 
// Commit list properties and the new columns.
list.Update();
 
// Modify the default view.
SPView view = list.DefaultView;
view.ViewFields.Add("field1");
view.ViewFields.Add("field2");
view.ViewFields.Add("field3");
view.ViewFields.Add("field4");
view.ViewFields.Add("field5");
view.Update();

Create Lists and Libraries

Create a document library:

SPWeb web = SPContext.Current.Web;
Guid libId = web.Lists.Add("Lib Title", "Description", SPListTemplateType.DocumentLibrary);
SPDocumentLibrary lib = web.Lists[libId] as SPDocumentLibrary;
lib.OnQuickLaunch = true;
lib.ContentTypesEnabled = true;
lib.BreakRoleInheritance(true);
lib.Update();

Create a list or a library from a template:

// Input parameters:
// - listName (string)
// - listDesc (string)
// - templName (string)
// - isLibrary (bool)
 
// Try to find the list template among built-in templates.
SPListTemplate listTemplate = 
    SPContext.Current.Web.ListTemplates.Cast<SPListTemplate>()
    .Where(tmpl => tmpl.Name == tmplName).FirstOrDefault();
 
// If it's not a built-in template, try to find it among custom templates.
if (listTemplate == null)
{
    SPListTemplateCollection customTemplates = 
        SPContext.Current.Site.GetCustomListTemplates(SPContext.Current.Web);
    listTemplate = customTemplates.Cast<SPListTemplate>()
        .Where(tmpl => tmpl.Name == templName).FirstOrDefault();
}
 
if (listTemplate == null)
    throw new ArgumentException("Template '" + tmplName + "' not found.");
 
// Create the list.
SPListCollection lists = SPContext.Current.Web.Lists;
Guid listId = Guid.Empty;
 
if (isLibrary)
{
    SPDocTemplateCollection documentTemplates = SPContext.Current.Web.DocTemplates;
    SPDocTemplate docTemplate = 
        documentTemplates.Cast<SPDocTemplate>()
        .Where(tmpl => tmpl.Name == "None").FirstOrDefault();
    listId = lists.Add(listName, listDesc, listTemplate, docTemplate);
}
else
{
    listId = lists.Add(listName, listDesc, listTemplate);
}
 
// Modify some properties of the newly created list (or the library).
SPList list = SPContext.Current.Web.Lists[listId];
list.OnQuickLaunch = false;
list.EnableVersioning = true; // for document library
list.Update();

Create a Promoted Links list 'My Pages' (SP 2013):

// Get the Promoted Links list template.
//'web' is an SPWeb.
SPListTemplate template = web.ListTemplates["Promoted Links"];
 
// Check if our custom list exists.
SPList list = web.Lists.TryGetList("My Pages");
if (list == null)
{
    var links = new[]
    {
        new { Title = "Link1", PageUrl = "_layouts/15/Page1.aspx", ImageUrl = "_layouts/15/images/link1.png"},
        new { Title = "Link2", PageUrl = "_layouts/15/Page2.aspx", ImageUrl = "_layouts/15/images/link2.png"},
        new { Title = "Link3", PageUrl = "_layouts/15/Page3.aspx", ImageUrl = "_layouts/15/images/link3.png"}
    };
 
    // Create a new Promoted Links list
    Guid listId = web.Lists.Add("My Pages", "My Pages", template);
    list = web.Lists[listId];
 
    int order = 1;
    foreach (var link in links)
    {
        SPListItem item = list.Items.Add();
        item["Title"] = link.Title;
 
        string linkUrl =
            SPUrlUtility.CombineUrl(
                SPUrlUtility.CombineUrl(web.Site.Url, web.Name),
            link.PageUrl);
        item["LinkLocation"] = linkUrl;
 
        string imageUrl =
            SPUrlUtility.CombineUrl(
                SPUrlUtility.CombineUrl(web.Site.Url, web.Name),
            link.ImageUrl);
        item["BackgroundImageLocation"] = imageUrl;
 
        item["TileOrder"] = (double)order;
        ++order;
 
        item.Update();
    }
}

Change the order and the launch behaviour of tiles in a promoted links list using PowerShell:

cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
     Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
 
$sourceWebURL = "http://your_server_url"
$sourceListName = "My Links"
 
$web = Get-SPWeb -Identity $sourceWebURL
$list = $web.Lists[$sourceListName]
$items = $list.Items
 
foreach ($item in $items) {
    $item["Launch Behavior"]= $list.Fields["Launch Behavior"].GetFieldValue("New tab");
 
    if ($item["Title"] -eq "Link1") {
        $item["TileOrder"] = 1
    }
 
    if ($item["Title"] -eq "Link2") {
        $item["TileOrder"] = 2
    }
 
    if ($item["Title"] -eq "Link3") {
        $item["TileOrder"] = 3
    }
 
    $item.Update()
}
 
Write-Host 'Success!'
notes/sharepoint2010/lists_and_libraries.txt · Last modified: 2016/10/19 by admin