Here steps to create a new list through code & insert items.
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleServerObjectModel
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
// Create List
Guid newGuid = web.Lists.Add("Employees", string.Empty, SPListTemplateType.Contacts);
// Get reference to List
SPList list = web.Lists[newGuid];
list.OnQuickLaunch = true;
list.Update();
// Insert items into List
SPListItem item = list.AddItem();
item["Title"] = "Mr.";
item["First Name"] = " First Name ";
item["Last Name"] = " Last Name ";
item.Update();
} } }
} }
Step 4: Execute Application
Press F5 button to execute the application. Wait for the execution to complete.
Step 5: Verify New List
Now open your SharePoint site (based on URL) & verify the new list is created
Click on the Employees list & you can see the new item
This is small example of using Server Object Model to create a list & insert item.
Update & Delete
Following are the code for Update & Delete items.
private static void Update()
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Employees"];
// Insert items into List
SPListItem item = list.Items[0];
item["First Name"] = "Fahadullah";
item.Update();
} }
}
private static void Delete()
{
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Employees "];
// Insert items into List
SPListItem item = list.Items[0];
item.Delete();
} }
}
Thank you very much
Fahadullah Karimi
SharePoint Specialist
Object Model in SharePoint 2013 | Using SharePoint Server Object Model in Windows Application |
No comments:
Post a Comment