SharePoint 2010 Delete items from List by using C#

If you want to delete all items in a list or empty / truncate the list by using c# you might be interested in this small script:

SPList targetList = web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, "/Lists/YourList"));
SPList delList = web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, "/Lists/YourList"));
//If list is empty, do nothing, otherwise delete all items
if (targetList.ItemCount > 0)
foreach(SPListItem delItem in targetList.Items)

The trick is that we get our list two times. First time to iterate through the list, second time to delete the list item. That prevents errors like Index out of range, etc.


The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

Karsten Schneider
About Karsten Schneider 302 Articles
He is Consultant for SharePoint Solutions for collaboration, communication and business processes. He provides his customers applications based on standard features as well as development or combining the power of several microsoft tools like Dynamics CRM. In his free time he tries to collect tipps and worthy experience in this blog.