Tuesday, May 29, 2012

Update existing sharepoint list item programmatically


Here is steps to update existing sharepoint list item programmatically.

- Follow the steps to insert new item into your sharepoint list.

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.Url.ToString()))
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{

- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];

- Create new query object to hold query which fetches list item of the list
SPQuery SPMyQuery = new SPQuery();

- Assign query with value to it in ID field of the list item
SPMyQuery.Query = string.Format(“
< Where >  < Eq >  < FieldRef Name='ID' / >  < Value Type='Counter' > {0} < /Value >  < /Eq >  < /Where > ”,1); 

- Assign query to list and get item on the basis of the query build above
SPListItemCollection common = SPLData.GetItems(SPMyQuery);

- Check whether list collection contains result of the query, if contains item the proceed to update value of the list item
if (common.Count > 0)
{

- Set allowunsafeupdates for web to true
web.AllowUnsafeUpdates = true;


- Get first list item from the result list
SPListItem item = common[0];

- Set new value for the column which we want to update
item["Title"] = “New Value”;

- Update item which will add new item to list
item.Update();
}
}
}

-That’s it for updating existing item of sharepoint list.

No comments:

Post a Comment