Friday 17 February 2012

Sharepoint - Add or Delete List Items

Creating 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 items to, and four other text boxes that are used to specify the values to add. Indexers gather input from all five sources. The example also assumes that the list specified by TextBox1.Text exists.






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 by using the Add method of the collection. It then assigns 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. You can also use the Author, Editor, Created, and Modified fields as indexers, where Author or Editor specify a Microsoft SharePoint Foundation 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 an index into the collection as its parameter.





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.


No comments:

Post a Comment