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
Unable to find source-code formatter for language: csharp. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
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:
Unable to find source-code formatter for language: csharp. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
01: public static SPListItem OptimizedAddItem(SPList list)
02: {
03: const string EmptyQuery = "0";
04: SPQuery q = new SPQuery {Query = EmptyQuery};
05: return list.GetItems(q).Add();
06: }
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
Unable to find source-code formatter for language: csharp. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
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:))
{
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<PageLayout>(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
Unable to find source-code formatter for language: csharp. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
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];
SPFolder folder = web.Folders[sList];
SPFileCollection fcol = folder.Files;
string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
SPFile spf = web.GetFile(sTemplate);
byte[] binFile = spf.OpenBinary();
string destFile = fcol.Folder.Url + "/" + sFilename;
SPFile addedFile = fcol.Add(destFile, binFile, false);
SPItem newItem = addedFile.Item;
newItem["ContentType"] = sContentType;
newItem.Update();
addedFile.Update();
return true;
}
}
catch (SPException spEx)
{
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
Unable to find source-code formatter for language: csharp. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
SPList cal = site.Lists["Calendar"];
SPListItem calEvent = cal.Items.Add();
calEvent["Title"] = "Frequent Event";
string recurrence = "<recurrence><rule>" +
"<firstDayOfWeek>su</firstDayOfWeek>" +
"<repeat><daily dayFrequency='2?/></repeat>" +
"<windowEnd>2010-09-20T09:00:00Z</windowEnd>" +
"</rule></recurrence>";
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:
Unable to find source-code formatter for language: csharp. Available languages are: actionscript, html, java, javascript, none, sql, xhtml, xml
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();
}