Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

from the below codes, which one is best practice and performance wise also:-

CASE 1:

using (SPSite oSPsite = new SPSite("http://website url/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
      {
            oSPWeb.AllowUnsafeUpdates = true;

            // Fetch the List
            SPList list = oSPWeb.Lists["MyList"];

            //Add a new item in the List
            SPListItem itemToAdd = list.Items.Add();
            itemToAdd["Title"] = "Test Title";
            itemToAdd["Description"] = "Test Description";
            itemToAdd.Update();

            // Get the Item ID
            listItemId = itemToAdd.ID;

            // Update the List item by ID
            SPListItem itemToUpdate = list.GetItemById(listItemId);
            itemToUpdate["Description"] = "Changed Description";
            itemToUpdate.Update();

            // Delete List item
            SPListItem itemToDelete = list.GetItemById(listItemId);
            itemToDelete.Delete();

            oSPWeb.AllowUnsafeUpdates = false;
       }
}

Reference: http://www.mindfiresolutions.com/Add-Update-and-Delete-List-Items-Programmatically-in-Sharepoint-372.php

CASE 2:

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;

SPListItem item = listItems.Add();

item["Title"] = TextBox2.Text;
item["Stock"] = Convert.ToInt32(TextBox3.Text);
item["Return Date"] = Convert.ToDateTime(TextBox4.Text);
item["Employee"] = TextBox5.Text;

item.Update();
}

Reference: http://msdn.microsoft.com/en-us/library/office/ms467435(v=office.14).aspx. There is no mention of allow unsafe updates in this code? Is that OK?

share|improve this question
    
Was wondering why you won't use CSOM / JSOM? –  Sane.Amit Mar 21 at 7:05
    
What is the advantage> –  variable Mar 21 at 10:49
add comment

2 Answers 2

AllowUnsafeUpdates=true; is not required to add/delete/update list items unless you are doing these operations in Page_Load or other Get methods. Both CASE 1 and CASE 2 does not look good in terms of best practice. Problems with both case code:

Do not use oSPWeb.Lists["MyList"]; instead use oSPWeb.Lists.TryGetList("MyList1"); Do not use list.Items.Add(); instead use list.AddItem();

Always dispose objects (Best to use using(), done correctly in case 1, but try to avoid hard coded url if it is a webpart or user control etc)

Add null check for list object before using it.

Best practice code:

using (SPSite oSPsite = new SPSite("http://website url/"))//try not use hard code url unless no other option
            {
                using (SPWeb oSPWeb = oSPsite.OpenWeb())
                {
                    // Fetch the List
                    SPList list = oSPWeb.Lists.TryGetList("MyList1");
                    if (list != null)
                    {
                        //Add a new item in the List
                        SPListItem itemToAdd = list.AddItem();
                        itemToAdd["Title"] = "Test Title";
                        itemToAdd["Description"] = "Test Description";
                        itemToAdd.Update();

                        // Get the Item ID
                        listItemId = itemToAdd.ID;

                        // Update the List item by ID
                        SPListItem itemToUpdate = list.GetItemById(listItemId);
                        itemToUpdate["Description"] = "Changed Description";
                        itemToUpdate.Update();

                        // Delete List item
                        SPListItem itemToDelete = list.GetItemById(listItemId);
                        itemToDelete.Delete();
                    }
                }
            }

Always run sharepoint code analyser on your code.You can download it here

share|improve this answer
    
cool.. Can you provide any reference article for this..if possible –  variable Mar 21 at 6:41
1  
Also, do a new SPSite("http://website url/") only if you are accessing list from another site. Otherwise for current site, SPContext.Current.Web is always a better choice. –  Vardhaman Deshpande Mar 21 at 6:41
    
@Nachiket best way to learn this is by running SPCAF(SharePoint Code analysis Framework) on your code. I have added link to download it in the answer. –  Unnie Mar 21 at 6:46
2  
@VardhamanDeshpande Also keep in mind that SPContext does not exist in PowerShell. So when you have code (like a feature) that you want to activate through PowerShell, don't use SPContext. Bad example because features have their SPSite/Web/Others in the featureproperties. But Still :). –  Cameron Verhelst Mar 21 at 7:51
    
Should note that to get lists by Title is not the best choice always, since end users could change the Title. I usually use an extension on SPWeb for "TryGetList". Something like this: web.GetList(SPUtility.ConcatUrls(web.ServerRelativeUrl, "/Lists/MyList")) –  Anders Aune Mar 21 at 9:39
add comment

Both look same apart from the fact that AllowUnsafeUpdates is used in the second example. However, the better way of adding list items is SPList.AddItem() instead of SPList.Items.Add() See this for more explanation: SPList.Add() vs SPList.AddItem() SharePoint 2010

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.