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]

27 comments:

Ishai Sagi [SharePoint MVP] 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 [SharePoint MVP] said...

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

Unknown 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

B1ju 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);

B1ju 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

Furtive Bystander 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?

Anonymous 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..

Angelica Rose said...

I am definitely enjoying your website. You definitely have some great insight and great stories. architects London

Eliza Beth said...

I love the way you write and share your niche! Very interesting and different! Keep it coming! coin airdrop

aryanoone said...

Thanks for sharing such a nice Blog.I like it.
mcafee antivirus activation key
norton setup with product key
activate my norton product key
how to run mcafee unique product key
comcast support telephone number
AVG Antivirus toll free number
webroot antivirus support phone number
kaspersky contact number
Outlook support number
microsoft edge support number

Anonymous said...

Airdrops are a great way to earn tokens especially for beginners looking to get into the market, as long as you do the necessary research on the airdrops and make sure the project has potential.
You can find more info on airdrops here https://freecoins24.io

Erin Moses said...

Norton Support Phone Number
Comcast Support Phone Number
Mozilla firefox Customer Service Telephone Number
Microsoft Edge Customer Service Number

Seema Singh said...

Thanks for sharing such a Post!

Canon Printer Customer Service Phone Number USA
Epson Printer Tech Support Phone Number
HP Laserjet Printer Customer Care Number
Canon Printer Support Online
HP Printer Support Number
Canon Printer Customer Service Phone Number USA

Rachel Pike said...

Thanks for sharing such a Post!

Malwarebytes Customer Support
bitdefender support phone number
kaspersky customer service
webroot support phone number
Phone number for AVG Antivirus
Norton Support Phone Number

Kelly Cain said...

Interpages

Guest Blogger

Best Guest Blogging Site

Guest Posting Site

Guest Blogging Website

Riti Mallin said...

My travel life have been easier with Garmin GPS. Plus I can get all the additional knowledge through their blogs. I use the Garmin app and is totally upto the mark. I recommend everyone to use MyGarmin Express and get Garmin life time map update or call +1-888-309-0939 for instant help from Garmin GPS experts.

[email protected] said...

I never used all the features of Garmin Software. But still I can say that this is the best app I have ever used. Garnim Nuvi comes with some refined features. Check out Garmin Nuvi Update or call +1-888-309-0939 for instant help from Garmin GPS experts.

Aiden Jangra said...

I have read all the comments and suggestions posted by the visitors for this blog are very fine, We will wait for your next blog so only.Thanks! If you want to Fix HP support number in a quick time, get in touch via our Hp printer customer service helpline Number. Our team has HP support number experts who will help you around the clock, 24x7 support.

Roku Com Link said...

You are sharing such an awesome and fantastic post with us. I appreciate your effort to share the knowledge. I am so happy to find this Blog which has informative and quality content for reading. Thanks for sharing. If it doesn’t work then, you have to read about the nitty gritty about Roku.com/link activation code from the Internet. Hopefully, then, you can connect the device with the Roku activation code accordingly.

Bhavya gaur said...

For those who want Government Jobs Latest Update and news, this is the website to come. You can check here for the latest updates about govt job. On this website you can found  All India Govt Jobs Employment News of Central and State Government Jobs, Govt Undertaking, Public Sector, Railway and Bank Jobs In India.

Army Recruitment
Railway Jobs in India
Teaching Jobs
Govt Engineering Jobs
Bank Jobs in India
State Government Jobs

123456789 said...

They're not subject to any type regulation. Small groups love them, due to the fact there're no credit score card costs worried.How to recover your stolen bitcoin

Unknown said...

TechEschools is a community for IT professionals.We have built a platform where learning is going to be free and accessible to everyone around the globe. TechEschools.com is additionally an online learning platform that helps anyone to learn software, technology, and artistic skills to realize the private and professional goals.
TechEschools provide articles, tutorials, videos, and Ebooks associated with master software development technologies immediately. We are scaling up to other areas of education.
Visit : TechEschools

Garmin Express Update said...

Hi there! This blog post couldn’t be written much better! Reading through this blog reminds me of my previous roommate! He constantly kept talking about this. I most certainly will send this blog to him. Thanks for sharing! Know about Garmin.com/Express.

Garmin Express Update said...

You can download and install the Garmin.com/Express on your desktop from the link Garmin Express Update online. The software also allows you to transfer your daily activity and other data to the Garmin Express without any trouble. Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.