Add, Update, Delete & Display List items in Gridview Programmatically in SharePoint 2016

In this SharePoint server object model tutorial, we will discuss how we can insert or add, update, delete an item to the SharePoint list programmatically using SharePoint 2016 server object model code.

Here we will create a visual web part in SharePoint 2016 on-premise and then we will design an input form through which users can insert or add an item to the SharePoint list.

In the same way, you can insert an item to the SharePoint list programmatically in SharePoint 2013.

Also, we will see how we can use AllowUnsafeUpdates in SharePoint 2016 server object model and how to Update List Items Programmatically in SharePoint 2016, how to Delete List Items Programmatically using SharePoint 2016 server object model code and finally we will see how to display list data using gridview in SharePoint 2016.

Here I have a SharePoint 2016 list as Feedback (Custom List) which has below columns:

  • Title
  • LastName
  • EmailID
  • Feedbacks

Create Visual Web Part using Visual Studio in SharePoint 2016

Now we will first create a visual web part (farm solution) using visual studio 2017/2019, where we are going to design our form and we can write our SharePoint server object model code to save the data to the SharePoint list.

Open visual studio 2017, Click on File -> New -> Project…

Then in the New Project dialog box, choose Visual C# -> Office/SharePoint -> SharePoint Solutions and then choose SharePoint 2016 – Empty Project. Give a name for the Solution and choose a folder to save the solution. It should look like below:

add item to sharepoint list programmatically
add item to sharepoint list programmatically

Once click on OK, it will open the SharePoint Customization Wizard dialog box. Here you have to choose below things:

sharepoint list additem
sharepoint list additem
  • What site do you want to use for debugging? Here you need to provide a local SharePoint 2016 site. The site should be presented in the same server, remote Sites are not allowed here. Since we are going to use SharePoint server object model (Microsoft.SharePoint.dll), SharePoint 2016 should have to be installed in the same machine where you have installed visual studio 2016. You can optionally click on the “Validate” button to check if the website is valid. It will display a connection successful message if the website is valid.

If you are developing any SharePoint hosted add-in or Provider hosted add-in using visual studio 2017, then you can give remote SharePoint developer site URL like SharePoint Online developer site URL.

  • What is the trust level for this SharePoint Solution? Here either you can choose a Deploy as a Sandboxed solution, in this case, the solution will be deployed to a particular Site collection. Microsoft itself is not recommending to use Sandboxed solution anymore. The second option we can choose to use Deploy as a farm solution. Here I have chosen Deploy as a farm solution. Click on the Finish button which will create the solution.

Now our Empty solution will look like below:

SharePoint 2016 empty project
SharePoint 2016 empty project

Now we will add our visual web part project. For this Right on the project -> Add -> New Item… like below:

Add visual web part to SharePoint 2016
Add visual web part to SharePoint 2016

Then in the “Add New Item” dialog box, choose Visual C# Items -> “Visual web part (Farm Solution Only)” like below:

crud operations in sharepoint 2016
SharePoint 2016 visual web part

This will add a visual web part to the solution. The visual web part provides a user control (.ascx) file where we can add controls and code.

Design Feedback Input Form in Visual web part

We can add our controls and we can design the input form using server-side controls. Below is the code I have used to create the form.

<style type="text/css">
.auto-style1 {
width: 269px;
}
</style>
<h2>Give your Feedback</h2>
<table>
<tr>
<td class="auto-style1">First Name:</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td class="auto-style1">Last Name:
</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">Email ID:
</td>
<td>
<asp:TextBox ID="txtEmailID" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1">Comments/Feedback:
</td>
<td>
<asp:TextBox ID="txtFeedback" runat="server" Height="178px" TextMode="MultiLine" Width="426px"></asp:TextBox>
</td>
</tr>
<tr>
<td class="auto-style1"></td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /><br />
<asp:Label ID="lblResult" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>

Now we can write the code to save the data to the SharePoint list.

Insert Item to SharePoint 2016 List using Server Object Model C#.Net Code

Now we can write our code on how to add item in list in sharepoint 2016 programmatically. Below is the full code:

using Microsoft.SharePoint;
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
namespace Feedback.FeedbackVisualWebPart
{
public partial class FeedbackVisualWebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
//using (SPSite objSPSite = new SPSite("http://mypc/sites/MySP2016SiteCollection/"))
using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb objSPWeb = objSPSite.OpenWeb())
{
SPList objSPList = objSPWeb.Lists.TryGetList("Feedbacks");
if (objSPList != null)
{
SPListItem objSPListItem = objSPList.Items.Add();
objSPListItem["Title"] = txtFirstName.Text.Trim();
objSPListItem["LastName"] = txtLastName.Text.Trim();
objSPListItem["EmailID"] = txtEmailID.Text.Trim();
objSPListItem["Feedbacks"] = txtFeedback.Text.Trim();
objSPListItem.Update();
lblResult.Text = "Your feedback submitted successfully.";
Clear();
}
else
{
lblResult.Text = "The list is not exists.";
}
}
}
}
void Clear()
{
txtFirstName.Text = "";
txtLastName.Text = "";
txtEmailID.Text = "";
txtFeedback.Text = "";
}
}
}

Here we are adding the item to SharePoint list, then showing a successful message and then we are clearing the textboxes.

Deploy Visual Web Part to SharePoint 2016 Site

Now we will see how we can deploy our visual web part to SharePoint 2016 site. Right click on the Project and then click on Deploy like below:

crud operations in sharepoint 2013
Adding Items Into A SharePoint list Programmatically Using C#

Once it is deployed successfully, you can see a message like below:

—— Build started: Project: Feedback, Configuration: Debug Any CPU ——
Feedback -> E:\Bijaya\TrainingDemos\Feedback\Feedback\bin\Debug\Feedback.dll
Successfully created package at: E:\Bijaya\TrainingDemos\Feedback\Feedback\bin\Debug\Feedback.wsp
—— Deploy started: Project: Feedback, Configuration: Debug Any CPU ——
Active Deployment Configuration: Default
Skipping deployment step because a pre-deployment command is not specified.
Skipping application pool recycle because no matching package on the server was found.
Skipping package retraction because no matching package on the server was found.
Add Solution:
Adding solution ‘Feedback.wsp’…
Deploying solution ‘Feedback.wsp’…
Activate Features:
Activating feature ‘Feature1’ …
Skipping deployment step because a post-deployment command is not specified.
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========

add list item in c#
Add List Item To SharePoint List Using C#

This way we can deploy visual web part to local SharePoint site. But if you want to deploy visual web part to any other site where there will not be any visual studio then you can follow PowerShell Script to deploy WSP Solution in SharePoint 2013.

Test Functionality (Add Item to SharePoint List Programmatically)

Once our visual web part deployed successfully, we can now test our functionality.

First, we will create a Web Part page in SharePoint 2016. Then edit the web part page and click on Add a web part, Then in the Web Part Categories, we can see, “Custom“, and then we can our web part. Click on Add which will add the web part to the web part page.

how to add item in list in sharepoint 2013 programmatically
Add, Update and Delete List Items Programmatically

Now our form will look like below, where you can enter values and click on Submit button which will insert the item to SharePoint list.

Add, Update and Delete List Items Programmatically in SharePoint
Add, Update and Delete List Items Programmatically in SharePoint

Now to verify whether the list item has been added or not. Open the SharePoint list in the browser, you can see the item has been added like below:

how to add item in list in sharepoint 2013 programmatically
Add, Update and Delete List Items Programmatically in SharePoint 2016

AllowUnsafeUpdates in SharePoint 2016

According to MSDN, when you are trying to update to a content database as a result of a GET request you need to set AllowUnsafeUpdates to true.

For example, if you want to update something into a SharePoint list, then you need to set AllowUnsafeUpdates = true for the web and after an update has done, you need to set it back to false.

If you make AllowUnsafeUpdates = false, it will prevent it from cross-site scripting attacks.

Below is one of the best way to use AllowUnsafeUpdates in SharePoint server object model code.

protected void btnSubmit_Click(object sender, EventArgs e)
{
//using (SPSite objSPSite = new SPSite("http://mypc/sites/MySP2016SiteCollection/"))
using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb objSPWeb = objSPSite.OpenWeb())
{
bool allowUnsafeUpdate = objSPWeb.AllowUnsafeUpdates;
SPList objSPList = objSPWeb.Lists.TryGetList("Feedbacks");
if (objSPList != null)
{
objSPWeb.AllowUnsafeUpdates = true;
SPListItem objSPListItem = objSPList.Items.Add();
objSPListItem["Title"] = txtFirstName.Text.Trim();
objSPListItem["LastName"] = txtLastName.Text.Trim();
objSPListItem["EmailID"] = txtEmailID.Text.Trim();
objSPListItem["Feedbacks"] = txtFeedback.Text.Trim();
objSPListItem.Update();
lblResult.Text = "Your feedback submitted successfully.";
Clear();
objSPWeb.AllowUnsafeUpdates = allowUnsafeUpdate;
}
else
{
lblResult.Text = "The list is not exists.";
}
}
}
}

Update List Item Programmatically using SharePoint 2016 server object model

Now we will see how we can update list item using SharePoint 2016 server object model. For this example, I have just renamed the button as “Update Item” and on click of that button, we will see how we can update list item for a particular item id.

Here you can see below, the list has one item and the item id is 2. So we are going to update the item details whose ID=2.

how to update list item in sharepoint 2013 programmatically
Update list item in SharePoint

Below is the button click code.

Here we first retrieve the list item by Id and then we are updating the item.

SPListItem objSPListItem = objSPList.GetItemById(2);

I have had coded the ID, you can implement your logic to make the item id dynamic.

protected void btnSubmit_Click(object sender, EventArgs e)
{
//using (SPSite objSPSite = new SPSite("http://mypc/sites/MySP2016SiteCollection/"))
using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb objSPWeb = objSPSite.OpenWeb())
{
bool allowUnsafeUpdate = objSPWeb.AllowUnsafeUpdates;
SPList objSPList = objSPWeb.Lists.TryGetList("Feedbacks");
if (objSPList != null)
{
objSPWeb.AllowUnsafeUpdates = true;
SPListItem objSPListItem = objSPList.GetItemById(2);
objSPListItem["Title"] = txtFirstName.Text.Trim();
objSPListItem["LastName"] = txtLastName.Text.Trim();
objSPListItem["EmailID"] = txtEmailID.Text.Trim();
objSPListItem["Feedbacks"] = txtFeedback.Text.Trim();
objSPListItem.Update();
lblResult.Text = "Your feedback has been updated successfully.";
Clear();
objSPWeb.AllowUnsafeUpdates = allowUnsafeUpdate;
}
else
{
lblResult.Text = "The list is not exists.";
}
}
}
}
void Clear()
{
txtFirstName.Text = "";
txtLastName.Text = "";
txtEmailID.Text = "";
txtFeedback.Text = "";
}

Once I modified the code and deploy the wbe part, you can see here I have put the updated values like below:

update list item in sharepoint 2016 programmatically
Update List Items Programmatically in SharePoint

Once you click on Update Item, you can see the changes like below in the SharePoint Online list.

update list item in sharepoint 2013 programmatically
Update List Items Programmatically in SharePoint 2013

Display List Items in Gridview using SharePoint 2016 server object model

Now we will see, how we can display few list items using Gridview using SharePoint 2016 server object model in SharePoint 2016 site. Here I will take one additional button as “Display List Items” and on click on that, it will display all the items in a Gridview.

Here into that SharePoint list, I have added few items into it and the list now looks like below:

Display List Items Programmatically in SharePoint 2013
Display List Items Programmatically in SharePoint 2013

Below is the full code to retrieve the list items and display using grid view in SharePoint 2016.

.ASPX Code:

<h2>Dispay SharePoint List Items</h2>
<asp:Button ID="btnDisplayListDate" runat="server" Text="Display List Data" OnClick="btnDisplayListDate_Click" />
<br />
<br />
<asp:GridView ID="gvFeedbacks" runat="server"></asp:GridView>

C#.net Code:

protected void btnDisplayListDate_Click(object sender, EventArgs e)
{
using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb objSPWeb = objSPSite.OpenWeb())
{
SPList objSPList = objSPWeb.Lists.TryGetList("Feedbacks");
SPListItemCollection listItems = objSPList.GetItems();
gvFeedbacks.DataSource = listItems.GetDataTable();
gvFeedbacks.DataBind();
}
}
}

Once you deploy the code and click on the button it will display all the columns like below:

display sharepoint list items in gridview
Display List Items Programmatically in SharePoint 2016

Display List Items (Selected Columns) in Gridview using SharePoint 2016 server object model

We might not required to display all the columns from the SharePoint list in the grid view. Suppose here I want to display only below columns.

  • Firnat Name (Title)
  • Last Name
  • Email ID
  • Feedback

For this, we need to first create a data table at runtime and then bind the list data to the data table. Finally, we will bind the data table data to grid view.

Create Data Table:

Below is the code which we can use to create a data table in C#.Net.

DataTable dtFeedbacks = new DataTable();
dtFeedbacks.Columns.Add("ID", typeof(int));
dtFeedbacks.Columns.Add("First Name", typeof(string));
dtFeedbacks.Columns.Add("Last Name", typeof(string));
dtFeedbacks.Columns.Add("Email ID", typeof(string));
dtFeedbacks.Columns.Add("Feedbacks", typeof(string));

Here I have taken a separate button and another grid view to bind the data.

.ASPX Code:

<h2>Dispay SharePoint List Items</h2>
<asp:Button ID="btnBindSelectedColumns" runat="server" Text="Display List Data (Selected Columns)" OnClick="btnBindSelectedColumns_Click" />
<br />
<br />
<asp:GridView ID="gvSelectedColumnListData" runat="server"></asp:GridView>

C#.Net Code:

protected void btnBindSelectedColumns_Click(object sender, EventArgs e)
{
DataTable dtFeedbacks = new DataTable();
dtFeedbacks.Columns.Add("ID", typeof(int));
dtFeedbacks.Columns.Add("First Name", typeof(string));
dtFeedbacks.Columns.Add("Last Name", typeof(string));
dtFeedbacks.Columns.Add("Email ID", typeof(string));
dtFeedbacks.Columns.Add("Feedbacks", typeof(string));
using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb objSPWeb = objSPSite.OpenWeb())
{
SPList objSPList = objSPWeb.Lists.TryGetList("Feedbacks");
SPListItemCollection listItems = objSPList.GetItems();
foreach (SPItem item in listItems)
{
DataRow dr = dtFeedbacks.NewRow();
dr["ID"] = Convert.ToInt16(item["ID"]);
dr["First Name"] = item["Title"].ToString();
dr["Last Name"] = item["LastName"].ToString();
dr["Email ID"] = item["EmailID"].ToString();
dr["Feedbacks"] = Regex.Replace(item["Feedbacks"].ToString(), "<.*?>", String.Empty);
dtFeedbacks.Rows.Add(dr);
}
gvSelectedColumnListData.DataSource = dtFeedbacks;
gvSelectedColumnListData.DataBind();
}
}
}

You can see below when user clicks on the column, instead of showing all the columns, it is showing me only selected columns. And for the multilne Feedbacks columns, we are removing the HTML tags like below:

Regex.Replace(item["Feedbacks"].ToString(), "<.*?>", String.Empty);
display sharepoint list items in gridview
Retrieve List Items Programmatically in SharePoint 2016 C#.Net

Delete List Items Programmatically in SharePoint 2016

Now we will discuss how we can Delete List Items Programmatically in SharePoint 2016 or SharePoint 2013. Here we will delete list items by ID using SharePoint 2016 server object model code.

We will provide a text box and a button where user can enter the item id an then click on the Dlete Item button which will delte the item from the list.

.ASPX code:

<h2>Delete SharePoint List Item by Item ID</h2>
<br />
<br />
<table>
<tr>
<td class="auto-style1">Enter List Item ID</td>
<td>
<asp:TextBox ID="txtItemID" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td>
<asp:Button ID="btnDeleteListItem" runat="server" Text="Delete List Item" OnClick="btnDeleteListItem_Click" />
<asp:Label ID="lblDeleteStatus" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>

C#.Net Code

protected void btnDeleteListItem_Click(object sender, EventArgs e)
{
using (SPSite objSPSite = new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb objSPWeb = objSPSite.OpenWeb())
{
bool allowUnsafeUpdate = objSPWeb.AllowUnsafeUpdates;
SPList objSPList = objSPWeb.Lists.TryGetList("Feedbacks");
if (objSPList != null)
{
objSPWeb.AllowUnsafeUpdates = true;
SPListItem objSPListItem = objSPList.GetItemById(Convert.ToInt16(txtItemID.Text.Trim()));
objSPListItem.Delete();
lblDeleteStatus.Text = "Item with ID: " + txtItemID.Text+" deleted successfuly.";
objSPWeb.AllowUnsafeUpdates = allowUnsafeUpdate;
}
else
{
lblDeleteStatus.Text = "The list is not exists.";
}
}
}
}

User will enter Item Id and click on the button to Delete, it will show a successful message once the deleteion successful.

Delete List Items Programmatically in SharePoint
Delete List Items Programmatically in SharePoint

Now once you will open the SharePoint list, you can see the item with ID = 5 is not presented in the list.

Delete List Items Programmatically in SharePoint 2016
Delete List Items Programmatically in SharePoint 2016

Download Source Code

You can also download the full source code here. The solution does not contain the dlls, you can just add the dlls into the solution.

[thrive_leads id=’5014′]

Read some SharePoint tutorials:

Conclusion

Here we had discussed below topics:

  • How to create a visual web part in SharePoint 2016 using Visual Studio 2016 and how to deploy visual web part to SharePoint 2016?
  • Add, Update and Delete List Items Programmatically in SharePoint 2016
  • Display list items using gridview in SharePoint 2016
  • How to use AllowUnsafeUpdates in SharePoint 2016?
  • How to use SharePoint 2016 server object model code to insert, update, delete and display list items?
>