Mar 27, 2012

spWeb.Lists vs spWeb.GetList

// Best Practice To Retrieve List Item
// Below example updates the Task list Item based on the task id

 ....
SPSecurity.RunWithElevatedPrivileges(delegate()
{
        using (SPSite oSiteCollection = new SPSite(url))
        {
                        using (SPWeb spWeb = oSiteCollection.OpenWeb())
                        {
                            spWeb.AllowUnsafeUpdates = true;
                            SPList oList = spWeb.Lists["New_Task_List"]; // Gets the entire List Collection and then picks the list mentioned
                            SPListItem oListItem = oList.GetItemById(taskid);

                           //Instead the following should be used, get the intended list directly
                           //SPListItem oListItem = spWeb.GetList("/Lists/New_Task_Lis/AllItems.aspx").GetItemById(taskid);

                            if (oListItem != null)
                            {
                                oListItem["flag"] = Guid.NewGuid().ToString();
                                oListItem["actiontaken"] = "Claim";
                                oListItem["actiontakenby"] = CustomUtility.GetUtility().GetLoggedInUserID();
                                oListItem.Update();
                            }
                            tempID = Convert.ToInt64(oListItem["TicketNumber"].ToString());
                        }
                    }
                });
...

Pages