How to: Add or Delete List Items
To add items to a list, use the Add method of the SPListItemCollection class to create an item object, and then use the Update method of the SPListItem class to update the database with the new item.
The following example assumes the existence of five text boxes, one that specifies the name of the list to add to, and four others that are used to specify the values to add. Indexers are used to gather the input from all five sources.
Note:
|
|---|
|
The code examples in this topic use members of the Microsoft.SharePoint.SPContext class to obtain the current site collection, Web site, or list. Outside of an HTTP context, such as in a console application or a Windows application, you obtain references to key objects with a different method. For more information, see Getting References to Sites, Web Applications, and other Key Objects. |
SPWeb mySite = SPContext.Current.Web; SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items; SPListItem item = listItems.Add(); item["Title"] = TextBox2.Text; item["Stock"] = Convert.ToInt32(TextBox3.Text); item["Return Date"] = Convert.ToDateTime(TextBox4.Text); item["Employee"] = TextBox5.Text; item.Update(); }
The example first creates an SPListItem object through the Add method of the collection. It then assign values to specific fields by using an indexer on the list item. For example, item["Title"] specifies the Title column value for the item. Finally, the example calls the Update method of the list item to effect changes in the database.
The previous example requires a using directive (Imports in Microsoft Visual Basic) for the Microsoft.SharePoint namespace.
To create list items with metadata that will be preserved, you can use the Author, Editor, Created, and Modified fields as indexers, where Author or Editor specify a Windows SharePoint Services user ID. For an example, see the SPListItem class.
To delete items from a list, use the Delete method of the SPListItemCollection class, which takes as its parameter an index into the collection.
SPWeb mySite = SPContext.Current.Web; SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items; int itemCount = listItems.Count; for (int k=0; k<itemCount; k++) { SPListItem item = listItems[k]; if (TextBox2.Text==item["Employee"].ToString()) { listItems.Delete(k); } }
Based on input from two text boxes, the example iterates through the collection of items for the specified list and deletes an item if the Employee field value matches the specified value.
The previous example requires a using directive (Imports in Visual Basic) for the Microsoft.SharePoint namespace.
See Also
using
(SPWeb web = SPContext.Current.Site.OpenWeb("/")){
SPList list = web.GetList("/subsite/Lists/list1");Context.Response.Write(
"Total items: " + list.ItemCount + "<BR>");Context.Response.Write(
"Deleting Items....");web.AllowUnsafeUpdates =
true; foreach (SPListItem item in list.Items){
item.Delete();
list.update();
}
web.AllowUnsafeUpdates =
false;}
- 9/30/2009
- ch15patel
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security;
using Microsoft.SharePoint;
[assembly: AllowPartiallyTrustedCallers]
namespace BasicWebPartst
{
public class HelloWorld : WebPart
{
TextBox txtBoxtitle, txtBoxCity, txtBoxID;
//protected override void Render(HtmlTextWriter writer)
//{
// writer.Write("hi!");
//}
protected override void CreateChildControls()
{
base.CreateChildControls();
InitializeComponents();
}
private void InitializeComponents()
{
Label lbltest = new Label();
lbltest.Text = "Fill the below table to populate the List";
this.Controls.Add(lbltest);
this.Controls.Add(new LiteralControl("<br>"));
this.Controls.Add(new LiteralControl("<br>"));
Table t = new Table();
t.BorderStyle = BorderStyle.Dotted;
t.BorderWidth = 1;
t.Width = 400;
# region Row1
//row 1
TableRow tr1 = new TableRow();
TableCell tc11, tc12;
tc11 = new TableCell();
tc12 = new TableCell();
tc11.Text = "Title: ";
tc11.Width = 100;
tc11.ColumnSpan = 1;
tc12.Width = 300;
tc12.ColumnSpan = 3;
txtBoxtitle = new TextBox();
txtBoxtitle.Width = 300;
tc12.Controls.Add(txtBoxtitle);
tr1.Cells.Add(tc11);
tr1.Cells.Add(tc12);
#endregion
#region Row2
//row 2
TableRow tr2 = new TableRow();
TableCell tc21, tc22;
tc21 = new TableCell();
tc22 = new TableCell();
tc21.Text = "City: ";
tc21.Width = 100;
tc22.Width = 300;
tc21.ColumnSpan = 1;
tc22.ColumnSpan = 3;
txtBoxCity = new TextBox();
txtBoxCity.Width = 300;
tc22.Controls.Add(txtBoxCity);
tr2.Cells.Add(tc21);
tr2.Cells.Add(tc22);
#endregion
#region Row3
//row 3
TableRow tr3 = new TableRow();
TableCell tc31, tc32;
tc31 = new TableCell();
tc32 = new TableCell();
tc31.ColumnSpan = 1;
tc32.ColumnSpan = 3;
tc31.Text = "ID: ";
tc31.Width = 100;
tc32.Width = 300;
txtBoxID = new TextBox();
txtBoxID.Width = 300;
tc32.Controls.Add(txtBoxID);
tr3.Cells.Add(tc31);
tr3.Cells.Add(tc32);
#endregion
#region Row4
//row 4
TableRow tr4 = new TableRow();
TableCell tc41, tc42, tc43,tc44;
tc41 = new TableCell();
tc42 = new TableCell();
tc43 = new TableCell();
tc41 = new TableCell();
tc42 = new TableCell();
tc44 = new TableCell();
tc41.Width = tc42.Width = tc43.Width = tc44.Width = 100;
tc41.ColumnSpan = tc42.ColumnSpan = tc43.ColumnSpan = 1;
Button BtnAdd = new Button();
BtnAdd.Text = " Add Item";
BtnAdd.Click += new EventHandler(BtnAdd_Click);
Button BtnDelete = new Button();
BtnDelete.Text = " Delete Item";
BtnDelete.Click += new EventHandler(BtnDelete_Click);
Button BtnSearch = new Button();
BtnSearch.Text = " Search Item";
BtnSearch.Click += new EventHandler(BtnSearch_Click);
Button BtnReset = new Button();
BtnReset.Text = " Reset";
BtnReset.Click += new EventHandler(BtnReset_Click);
BtnAdd.Width = BtnDelete.Width = BtnReset.Width = BtnSearch.Width= 100;
tc41.Controls.Add(BtnReset);
tc42.Controls.Add(BtnAdd);
tc43.Controls.Add(BtnDelete);
tc44.Controls.Add(BtnSearch);
tr4.Cells.Add(tc41);
tr4.Cells.Add(tc42);
tr4.Cells.Add(tc43);
tr4.Cells.Add(tc44);
#endregion
t.Rows.Add(tr1);
t.Rows.Add(tr2);
t.Rows.Add(tr3);
TableRow trblank = new TableRow();
t.Rows.Add(trblank);
t.Rows.Add(tr4);
this.Controls.Add(t);
}
void BtnSearch_Click(object sender, EventArgs e)
{
ClearForm();
if (string.IsNullOrEmpty(txtBoxID.Text))
{
return;
}
SPWeb currentWeb = SPContext.Current.Web;
currentWeb.AllowUnsafeUpdates = true;
SPList list = currentWeb.Lists["VivekList"];
SPListItem temp = null;
try
{
temp = list.Items.GetItemById(Convert.ToInt16(txtBoxID.Text));
}
catch { };
if (temp != null)
{
txtBoxtitle.Text = temp["Title"].ToString();
txtBoxCity.Text = temp["City"].ToString();
}
}
void BtnReset_Click(object sender, EventArgs e)
{
ClearForm();
}
private void AddItem(string StrTitle, string StrCity)
{
SPWeb currentWeb = SPContext.Current.Web;
currentWeb.AllowUnsafeUpdates = true;
SPList list = currentWeb.Lists["VivekList"];
SPListItem newListItem = list.Items.Add();
newListItem["Title"] = StrTitle;
newListItem["City"] = StrCity;
newListItem.Update();
txtBoxID.Text = Convert.ToString( newListItem.ID);
}
void BtnDelete_Click(object sender, EventArgs e)
{
//don't delete if item id is blank
if (String.IsNullOrEmpty(txtBoxID.Text))
{
return;
}
SPWeb currentWeb = SPContext.Current.Web;
currentWeb.AllowUnsafeUpdates = true;
SPList list = currentWeb.Lists["VivekList"];
list.Items.DeleteItemById(Convert.ToInt16(txtBoxID.Text));
ClearForm();
}
private void ClearForm()
{
txtBoxID.Text = "";
txtBoxCity.Text = "";
txtBoxtitle.Text = "";
}
void BtnAdd_Click(object sender, EventArgs e)
{
//Empty items dont add
if (string.IsNullOrEmpty(txtBoxtitle.Text) || string.IsNullOrEmpty(txtBoxCity.Text))
{
return;
}
AddItem(txtBoxtitle.Text, txtBoxCity.Text);
}
}
}
- 3/20/2009
- Vivek.Kumar
- 4/18/2009
- Stanley Roark
None of the samples given in the article or comments worked for me. The closest was Madhawak's but i found it was not quite right because the item ID was always 1 too many and the final list item never gets examined.
Here is the version that has worked for me.
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;
int itemCount = listItems.Count;
for (int k=itemCount; k>0; k--)
{
int id = k - 1;
SPListItem item = listItems[id];
listItems.Delete(id);
}
- 4/7/2009
- Martin Kearn - Microsoft UK
In that kinda situations you can start delete from the last item. Like below, It's an easy and a clean approach. You won't receive a boundary exceeded exception.
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists[TextBox1.Text].Items;
int itemCount = listItems.Count;
for (int k=itemCount-1; k>0; k--)
{
SPListItem item = listItems[k];
listItems.Delete(k);
}
- 9/16/2008
- Madhawak
If you need to loop through the ListItemCollection to delete multiple lListItems, your code will not work. When you attempt to delete the last ListItem, you will receive a boundary exceeded exception. The index to the ListItemCollection should always = 0. The following is sample code that will work:
int itemCount = listItems.Count;
bool done = false;
while (done == false)
{
if (itemCount < 1)
{
done = true;
break;
}
else
{
listItems.Delete(0);
itemCount--;
}
}
- 3/3/2008
- Fred Grau
Actually to be correct the code works fine. The reason the code did not work for you is that you are using it in a different manner then this example presents. You were wanting to pass a value in for the web location which is fine but the code in this article is retreving the data from the current site as you can see in the code where it says
"SPWeb mySite = SPContext.Current.Web;"
So if you compiled this code as a webpart and then added it to a SharePoint web you would see that it retrieves the current web as the "spweb" parameter. I think Microsoft should explain that in the article for people that are new to SharePoint. Others like myself have been working with it for years and understand these things already.
- 2/21/2008
- You Big Dummy
- 2/21/2008
- You Big Dummy
http://msdn2.microsoft.com/en-us/library/ms460897.aspx
That seemed to work. One thing that I did notice was there is an error in the code example on this other page as well. It says you should create an object:
myWebService.WebApplications["SharePoint - 80"].Sites["mySiteCollection"].OpenWeb["myWebSite"]
Since 'OpenWeb' is a method the square brackets should be parenthesis. This was a major stumbling block for me.
- 6/27/2007
- RHollister
Note: