Tuesday, 3 April 2007

Programmatically adding items to a SharePoint list

[Edited Version modified on the 4th April to take into account comments]

I strongly recommend you read the comment from Ishai at the bottom of this post (or just take a look at his very good blog).

The code below was primarily meant to be an example of how to add a description to a url and this is a heavily modified version of the code I was sent to blog about, so it hasn’t been used in the manner I have shown below - however Ishai is quite correct in the flaws he has pointed out.

The corrected code taken into account the comment he made can be seen below:-

protected void InsertEnquiryToSharepoint()
{
string strDashListRoot = "http://spSite/SubSite/Lists/MyList/";
using(SPSite site = new SPSite(strDashListRoot))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyList"];
SPListItem Item = list.Items.Add();
item["Title"] = txtCompanyName.Text;
item["DateReceived"] = System.DateTime.Now;
item["Description"] = txtDescription.Text;
//Important: Comma and space required to add the description
item["EnquiryDetail"] = "http://spSite/SubSite/ListProcess/Assign.aspx?EnquiryID=" + m_iEnquiryId + ", " + txtCompanyName.Text;
item.Update();
iListItemId = item.ID;
}
}
}
I will ask the guys in the office who wrote the original code to see if this still works for them, and maybe ask them to leave a comment about why they need to elevate permissions.

Thanks again Ishai for your comments - Thats what I love so much about blogging, it is definitely two way learning:)


[Original Post]

Couple of interesting things to note here - it is especially difficult to add a description to a url, as shown in the code below you have to separate the url with a comma and a space, for example
"http://www.waterstons.co.uk/" + ", " + "Waterstons"
And the second thing of interest is the fact that you have to elevate privileges in order to get the item you will be adding, but you must drop out otherwise you will not be able to save it later on.
protected void InsertEnquiryToSharepoint()
{
string strDashListRoot = "http://spSite/SubSite/Lists/MyList/";
string strRoot = "http://spSite/";
SPSite site = new SPSite(strRoot);
m_oSite = new SPSite(strDashListRoot).OpenWeb();
m_oSite.AllowUnsafeUpdates = true;
SPListItemCollection myListCol = m_oSite.Lists["MyList"].Items;
SPListItem item = null;
//Important: Need to elevate privileges to create the list item, but cant update the item
//unless I drop out of here.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
item = myListCol.Add();
});
item["Title"] = txtCompanyName.Text;
item["DateReceived"] = System.DateTime.Now;
item["Description"] = txtDescription.Text;
//Important: Comma and space required to add the description
item["EnquiryDetail"] = "http://spSite/SubSite/ListProcess/Assign.aspx?EnquiryID=" + m_iEnquiryId + ", " + txtCompanyName.Text;
item.Update();
iListItemId = item.ID;
m_oSite.AllowUnsafeUpdates = false;
}
Enjoy:)

Ross

[Thanks & credit to Paul Devenny and David Challener for the info in this post]

10 comments:

Ishai Sagi said...

You are not using best practice code:
1. you dont need to specify the root site seperately. you can use the same URL for the list in your code.
2. you are not disposing of the SPSite and SPWeb objects, and can cause a potential memory leak.
3. I dont see any need for the elevated privilages. why do you use it?

here is a code sample of the same, with best practice methods:

string strDashListRoot = "http://spSite/SubSite/Lists/MyList/";
using(SPSite site = new SPSite(strDashListRoot))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyList"];
SPListItem new Item = list.Items.Add();
item["Title"] = ....
...
...
item.Update();
}
}

The "using" is for disposing of the objects once code is run, and if you get the list directly you'r code will make more sense.

See my post in my blog about common tasks in sharepoint:
http://www.sharepoint-tips.com/2006/08/common-and-simple-coding-tasks-in.html

Ishai Sagi [MVP]

Ishai Sagi [MVP] said...

Anytime! keep up the good work. I will add you to my blogroll.

Charan said...

Hi,

I am using same piece of code to create ListItems and it was working absolutely fine. Suddenly we started receiving error which says,

"Value does not fall within the expected range"

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Value does not fall within the expected range.

The same piece of code was working till now. I am totally out of ideas, pleae help.

-Charan

Biju said...

I have a requirement to delete the webpart from the gallery on deactivating an feature(it is feature for customizing list event handler).
I do it using the following code,


using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["Web Part Gallery"];
for (int i = list.ItemCount - 1; i >= 0; i--)
{
if (list.Items[i].DisplayName.Equals("RegisterEventHandler"))
{
list.Items[i].Delete();

break;
}
}
}



Can you please suggest how to populate the webpart on activating the feature using

SPListItem Add(string folderUrl, SPFileSystemObjectType underlyingObjectType, string leafName);

Biju said...

Hi,
I had a webpart called RegisterEventHandler.webpart, which i have deleted from the SPListCollection

SPSite siteCollection = SPContext.Current.Site;
using (SPWeb siteRootWeb = siteCollection.RootWeb)
{
list = siteRootWeb.Lists["Web Part Gallery"];
if (list.Items[i].DisplayName.Equals("RegisterEventHandler"))
{
list.Items[i].Delete();
break;
}
}


Could you please suggest mehow to populate the webpart again into the gallery?

With regards

SEO Southampton said...

Thanks this usefully coding post this site. I like you're interesting blog. Because We have use this programming any feature time.
web designer hampshire

SAK said...

Hi,

Can you tell me where is the mapping for columns defined in Sharepoint? For example if i am using sharepoint in Swedish language, the content_types that i have defined, are in Swedish language. Will the code still work?

shalini said...

Incredibly excellent thank you, I do believe your trusty followers might probably want a fantastic deal more writing like that carry on the brilliant effort.
india domain registration

Adapt software India said...

SharePoint Online delivers the powerful features of SharePoint without the associated overhead of managing he infrastructure on your own. Flexible management options ensure that you still retain the control you need to meet the compliance requirements of your organization. You can purchase SharePoint in the cloud as a standalone offering or as part of an Office 365 suite where you could also get access to Exchange, Lync, the Office clients and web apps.
Sharepoint developer
Sharepoint Site
Sharepoint Services
Sharepoint Designer
Sharepoint Consulting
Sharepoint Server

Saad Zulfiqar said...

U need to use internal names for the field u are accessing..