Updating a List Item programmatically

Introduction:

In this article I am going to explain you how to update list item programmatically .
Also I will explain you that How to “update content type of list item programmatically” which is little tricky.

The Code:

Update List Item metadata:-

Get the SPListeItem object and update metdata. At lst never forget to use “SPListItem.update()”.
See sample code below:-

1
2
3
4
5
6
7
8
9
10
using(SPSite oSite = new SPSite("site url"))
{
	using(SPWeb oWebsite = oSite.OpenWeb())
	{
		SPList oList = oWebsite.Lists["Tasks"];
		SPListItem oListItem = oList.Items[5];
		oListItem["Title"] = "Some Title";
		oListItem.Update();// without this line item will not update
	}
}


Update List Item content type:-

Trick:- To update content type of list item, we need to assign content type id rather than content type name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using(SPSite oSite = new SPSite("site url"))
{
	using(SPWeb oWebsite = oSite.OpenWeb())
	{
		string cTypeName = "NewContentType";
		SPList oList = oWebsite.Lists["Tasks"];
		// get content type id
		SPContentType spCType = oList.ContentTypes[cTypeName];
		SPListItem oListItem = oList.Items[5];
 
		// below line will not update content type
		// oListItem["ContentType"] = “NewContentType”;
 
		// Correct implementation to apply new content type
		oListItem["ContentTypeId"] = spCType.Id.ToString();
		oListItem.Update();
	}
}

You may also like below article:-

how to delete items from sharepoint list programmatically
how to add items from sharepoint list programmatically
Get sharepoint list item programmatically

Thanks!
Avinash

calendarMarch 27, 2012 · cardInfoyen · comments2 Comments
tagTags: , , ,  · Posted in: List, MOSS, SharePoint

2 Responses

Leave a Reply

Spam Protection: , required

myworldmaps infoyen