It certainly isn't anything new and everything you can find at Microsoft documentation, but I just wanted to group some often used pieces of code onto one place. So it's mostly my knowledge base :)
ADD ITEM
------------------------------------
//Open site
using (SPSite site = new SPSite("http://yourSPSite"))
{
//Open web
using (SPWeb web = site.OpenWeb())
{
//Get your list
SPList list = web.Lists["TitleOfYourList"];
SPListItem listItem;
//Add new item to the list
listItem = list.Items.Add();
//Fill values in a new item
listItem["Title"] = "New title";
//Save it
listItem.Update();
}
}
UPDATE ITEM
------------------------------------
//Open site
using (SPSite site = new SPSite("http://yourSPSite"))
{
//Open web
using (SPWeb web = site.OpenWeb())
{
//Get your list
SPList list = web.Lists["TitleOfYourList"];
foreach (SPListItem item in list.Items)
{
if (item["Title"].ToString() == "YourTitleToUpdate")
{
//Change something
item["Title"] = "YourNewTitle";
//Save it
item.Update();
}
}
}
}
DELETE ITEM
------------------------------------
This part is little bit tricky and maybe it will not look like as you are expecting.
If you would use foreach loop to go through your items you would see error message like this: Collection was modified; enumeration operation may not execute. because whenever item is deleted the number of items in foreach loop is changed.
If you would use for loop and count upward you wouldn't get error message but if you would want to delete all items from the list some items would be skipped and remained in the list.
You should use for loop and count downward then you will be able to delete all items or just item depending on your condition.
//Open site
using (SPSite site = new SPSite("http://yourSPSite"))
{
//Open web
using (SPWeb web = site.OpenWeb())
{
//Get your list
SPList list = web.Lists["TitleOfYourList"];
//Count downward to go through all items
for (int i = list.Items.Count - 1; i >= 0; i--)
{
//Delete just the items with title "Test"
if (list.Items[i].Title == "Test")
{
Console.WriteLine("Deleting " + list.Items[i].Title);
list.Items.Delete(i);
}
}
}
}
Happy coding ;)
David
No comments:
Post a Comment