Saturday, February 26, 2011

SharePoint - Adding list Items Programmatically

Every list the SharePoint has list items. SPListItemCollection object is used to get the all list items in SharePoint .SPListItem is the class is used to store the list items. We can do the operations on list items through coding in SharePoint.

code snippet to Add the list items to list in SharePoint.
// Get The Lists in the site and add the items to that list
private static void AddListItems(string siteUrl)
{
  using (SPSite currentSite = new SPSite(siteUrl))
  {
     using (SPWeb currentWeb = currentSite.OpenWeb())
     {
        if(currentWeb.Exists()
        {
            Console.WriteLine("enter the title of the list to add the items");
            listTitle=console.ReadLine();
            if (string.IsNullOrEmpty(listTitle))
            {
                 Console.WriteLine("list item title not be empty"); 
            }
            else
            {
                 Console.WriteLine("enter the list Item title to add the list");
                 listItemTitle = Console.ReadLine();
                 if (string.IsNullOrEmpty(listItemTitle))
                 {
                       Console.WriteLine("list item title not be empty"); 
                 }
                 else
                 {
                      SPListItem listItem = currentWeb.Lists[listTitle].Items.Add();
                      listItem["Title"] = listItemTitle;
                      listItem.Update();
                  }
             }
        }
     }
  }
}

here we are getting the site url as the string and through that siteurl string opening the root web of the site. In SPList we have the Items property as ListItemCollecton object. We can add items by using the SPListItemCollction object.

we are using the using key words that to get dispose the SPSite and SPWeb objects. Because they are very big objects that they consume lot of the memory. So each time dispose the SPSite and SPWeb Objects in SharePoint.

Share this