Add and Display items from SharePoint list programmatically

This SharePoint tutorial explains, how to add an item to SharePoint list programmatically using SharePoint server object model code? We will also discuss how to display SharePoint list items using the server object model code.

We can use the same server object model code to insert and display SharePoint list items in SharePoint 2010/2013/2016.

In the previous example, I have explained:

Add an item to SharePoint list programmatically

Below is the code to add an item to a SharePoint list using the SharePoint server object model code. Here I have a SharePoint list name as MyCustomList. Here the list has 2 columns Title and Description.

The code we can use inside a visual web part in SharePoint.

try
{
SPSite myTopSite = SPContext.Current.Site;
{
SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
{
SPList listMyCustomList = myTopWeb.Lists.TryGetList("MyCustomList");

// TryGetList() is an useful method introduced in SharePoint.

if (listMyCustomList != null)
{
//Add item to list
myTopWeb.AllowUnsafeUpdates = true;
SPListItem newItem = listMyCustomList.Items.Add();
newItem["Title"] = "My Title";
newItem["Description"] = "My Short Description";
newItem.Update();
myTopWeb.AllowUnsafeUpdates = false;
}
}
}
}
catch(Exception ex)
{

}

Retrieve SharePoint list items programmatically using the SharePoint server object model

Now, we will see how to retrieve list items using the SharePoint server object model code.

SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
{
SPList listMenu = myTopWeb.Lists["MyCustomList"];

SPQuery objquery = new SPQuery();

objquery.Query = "<Where><Eq><FieldRef Name=’Title’ /><Value Type=’Text’>

EnjoySharePoint</Value></Eq></Where>";

SPListItemCollection items = listMenu.GetItems(objquery);

foreach (SPListItem item in items)
if (item != null)
{
if (item["Title"] != null)
{
if (!string.IsNullOrEmpty(item["Title"].ToString()))
{
string myTitle = item["Title"].ToString();
}
}
}
}

You may like following SharePoint server object model tutorials:

Here we have used CAML query with SPQuery class to retrieve items from SharePoint List. Here it will retrieve all list items whose Title is “EnjoySharePoint”.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>