Creating a List Item instance programmatically using the object model

本文详细介绍了如何使用对象模型在SharePoint 2007中创建列表项实例,包括添加到自定义列表的方法、优化的添加方法、带有附件的添加方法、添加到发布页面库的方法、添加到文档库的方法、添加到日历列表的方法、以及创建文档的方法等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://www.nothingbutsharepoint.com/sites/devwiki/sp2007dev/pages/creating%20a%20list%20item%20instance%20programmatically%20using%20the%20object%20model.aspx

The below code shows how to create a List Item programmatically using the object model in SharePoint 2007.

Adding a List Item to a Custom List

using (SPWeb web = siteCollection.AllWebs["webname"])
{
  SPList list = web.Lists["Custom List"];
  SPListItem item = list.Items.Add();
  item["Title"] = "New List Item";
  item.Update();
}


 

Optimised Adding a List Item to a Custom List

Use the following to add an item to a list:

public static SPListItem OptimizedAddItem(SPList list)
 {
 const string EmptyQuery = "0";
 SPQuery q = new SPQuery {Query = EmptyQuery};
 return list.GetItems(q).Add();
}


 

Do not use SPList.Items.Add as this will get all items in the list before adding a new SPListItem.

Source: Aidan Garnish

Adding a List Item to a Custom List with an Attachment

using (SPWeb web = siteCollection.AllWebs["webname"])
{
  SPList list = web.Lists["Custom List"];
  SPListItem item = list.Items.Add();
  item["Title"] = "New List Item";

  SPAttachmentCollection attachments = item.Attachments;
  attachments.Add(fileName, byteArrayContents);

  item.Update();
}


 

Adding a List Item to a Publishing Page Library

using (SPSite site = new SPSite("http://moss"))
{
    using (SPWeb web = site.OpenWeb())
    {
        PublishingSite pSite = new PublishingSite(site);
        SPContentType ctype = pSite.ContentTypes["Welcome Page"];
        PageLayoutCollection pageLayouts = pSite.GetPageLayouts(ctype, true);
        PageLayout pageLayout = pageLayouts.FirstOrDefault(p => p.Name == "WelcomeSplash.aspx");
        PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
        PublishingPageCollection pPages = pWeb.GetPublishingPages();
        PublishingPage pPage = pPages.Add("Programmatic_Test.aspx", pageLayout);
        SPListItem newpage = pPage.ListItem;
        newpage["Title"] = "Page added programmatically";
        newpage.Update();

        newpage.File.CheckIn("all looks good");
        newpage.File.Publish("all looks good");
    }
}


 

NOTE: requires .NET 3.5 for System.Linq FirstOrDefault method, can be switched for a loop.
Source: sridhara

Adding a List Item to a Document Library with an attachment

Source: Nick Grattan's SharePoint Blog

  
// Creates document in given list (root folder).
// Returns true if the file was created, false if it already
// exists or throws exception for other failure
protected bool CreateDocument( string sFilename, string sContentType, string sList)
{
    try
    {
        SPSite site = SPContext.Current.Site;

        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists[sList];
            // this always uses root folder
            SPFolder folder = web.Folders[sList];
            SPFileCollection fcol = folder.Files;

            // find the template url and open
            string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
            SPFile spf = web.GetFile(sTemplate);
            byte[] binFile = spf.OpenBinary();
            // Url for file to be created
            string destFile = fcol.Folder.Url + "/" + sFilename;

            // create the document and get SPFile/SPItem for
            // new document
            SPFile addedFile = fcol.Add(destFile, binFile, false);

            SPItem newItem = addedFile.Item;
            newItem["ContentType"] = sContentType;
            newItem.Update();
            addedFile.Update();
            return true;
        }
    }
    catch (SPException spEx)
    {
        // file already exists?
        if (spEx.ErrorCode == -2130575257)
            return false;
        else
            throw spEx;
    }
}


 

This code:

1. Gets a SPSite for the current site collection, and opens an SPWeb for the site.
2. Gets a SPList for the given list, and then an SPFolder for the root folder in this list. This code always creates the document in the root folder, but the code can easily be changed to place the document in any folder in the document library.
3. Gets a SPFileCollection for the documents in the folder.
4. "DocumentTemplateUrl" is used to return the Url of document template associated with the given content type.
5. Get an SPFile for the document template in spf and open it for binary access using OpenBinary
6. Add a new document to the folder through the SPFileCollection referenced by fcol.
7. Get an SPItem for the new document and set the "ContentType" column to ensure it uses the correct content type (it will default to the first content type in the document library).
8. Update the item and the added file.
9. The catch section checks for an -2130575257 error, which indicates the file already exists.

Adding a List Item to a Calendar List

Source: Andy - novolocus.com

SPList cal = site.Lists["Calendar"];
SPListItem calEvent = cal.Items.Add();
calEvent["Title"] = "Frequent Event";
string recurrence = "" +
"su" +
"" +
"2010-09-20T09:00:00Z" +
"";
calEvent["RecurrenceData"] = recurrence;
calEvent["EventType"] = 1;
calEvent["EventDate"] = new DateTime(2009, 1, 26, 8, 0, 0);
calEvent["EndDate"] = new DateTime(2009, 1, 26, 9, 0, 0);
calEvent["UID"] = System.Guid.NewGuid();
calEvent["TimeZone"] = 13;
calEvent["Recurrence"] = -1;


 

Note that the CAML to create the recurrence can be complicated so please take a look at the MSDN article.

Adding a List Item to a List in SharePoint 2010

In SharePoint 2010 you can use the following code to add an item to a SPList in an optimized way:

using (SPWeb web = SPContext.Current.Web)
{
  SPList list = web.GetList(string.concat(web.Url, "/Lists/Custom List"));
  SPListItem item = list.AddItem();
  item["Title"] = "New List Item";
  item.Update();
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值