Creating a List Item instance programmatically using the object model

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


 

MATLAB代码实现了一个基于多种智能优化算法优化RBF神经网络的回归预测模型,其核心是通过智能优化算法自动寻找最优的RBF扩展参数(spread),以提升预测精度。 1.主要功能 多算法优化RBF网络:使用多种智能优化算法优化RBF神经网络的核心参数spread。 回归预测:对输入特征进行回归预测,适用于连续值输出问题。 性能对比:对比不同优化算法在训练集和测试集上的预测性能,绘制适应度曲线、预测对比图、误差指标柱状图等。 2.算法步骤 数据准备:导入数据,随机打乱,划分训练集和测试集(默认7:3)。 数据归一化:使用mapminmax将输入和输出归一化到[0,1]区间。 标准RBF建模:使用固定spread=100建立基准RBF模型。 智能优化循环: 调用优化算法(从指定文件夹中读取算法文件)优化spread参数。 使用优化后的spread重新训练RBF网络。 评估预测结果,保存性能指标。 结果可视化: 绘制适应度曲线、训练集/测试集预测对比图。 绘制误差指标(MAE、RMSE、MAPE、MBE)柱状图。 十种智能优化算法分别是: GWO:灰狼算法 HBA:蜜獾算法 IAO:改进天鹰优化算法,改进①:Tent混沌映射种群初始化,改进②:自适应权重 MFO:飞蛾扑火算法 MPA:海洋捕食者算法 NGO:北方苍鹰算法 OOA:鱼鹰优化算法 RTH:红尾鹰算法 WOA:鲸鱼算法 ZOA:斑马算法
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值