Thursday, February 7, 2008

Add List items to a Custom List

Well, as you know, much of sharepoint's help looks like it was code generated. That's why we blog.

Anyway enough whining. I needed to add list items to a custom list (this one is from a feature activating event):


const SYSTEMSITEMENULISTTEMPLATENAME = "mycustomlist";
const SYSTEMSITEMENULINKSLISTDESCRIPTION = "description";

public void CreateSystemSiteMenuLinks(SPFeatureReceiverProperties properties, SPWeb curWeb)
{

//get instance of the list template from the web
SPListTemplate menuListTemplate = curWeb.ListTemplates[SYSTEMSITEMENULISTTEMPLATENAME];
//make a list with the template
curWeb.Lists.Add(SYSTEMSITEMENULINKSLISTNAME, SYSTEMSITEMENULINKSLISTDESCRIPTION, menuListTemplate);
//look up the custom content type
SPContentType systemMenuItemContentType = curWeb.Lists[SYSTEMSITEMENULINKSLISTNAME].ContentTypes["System Menu Item"];

//add item to the list, its actually for a menu site navigation on the My Site
AddMenuItems(curWeb.Lists[SYSTEMSITEMENULINKSLISTNAME].Items.Add(), "My Home", curWeb.Site.Url, systemMenuItemContentType.Id);
AddMenuItems(curWeb.Lists[SYSTEMSITEMENULINKSLISTNAME].Items.Add(), "My Profile", curWeb.PortalUrl + "", systemMenuItemContentType.Id);
AddMenuItems(curWeb.Lists[SYSTEMSITEMENULINKSLISTNAME].Items.Add(), "My Document", curWeb.PortalUrl + @"Person.aspx?accountname=" + System.Security.Principal.WindowsIdentity.GetCurrent().Name, systemMenuItemContentType.Id);
}


private void AddMenuItems(SPListItem sPListItem, string title, string menuUrl, SPContentTypeId systemMenuItemContentTypeId)
{

sPListItem["ContentTypeId"] = systemMenuItemContentTypeId;
sPListItem["Title"] = title;
sPListItem["Menu URL"] = menuUrl;

sPListItem.Update();
}

No comments: