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.
Dim mySite As SPWeb = SPContext.Current.Web
Dim listItems As SPListItemCollection
= mySite.Lists(TextBox1.Text).Items
Dim item As SPListItem = 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()
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.
Dim mySite As SPWeb = SPContext.Current.Web
Dim listItems As SPListItemCollection
= mySite.Lists(TextBox1.Text).Items
Dim itemCount As Integer = listItems.Count
Dim k As Integer
For k = 0 To itemCount - 1
Dim item As SPListItem = listItems(k)
If TextBox2.Text = item("Employee").ToString() Then
listItems.Delete(k)
End If
Next k
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