Sunday, October 31, 2010

Delete data items from Sharepoint list

Following code help you to delete the Sharepoint list items row by row.

private void DeleteRows()
{

string SPSiteName = "http://localhost";
string SPWebName = "";
string SPListName = "some_list";

try
{
using (SPSite site = new SPSite(SPSiteName))
{
using (SPWeb web = site.AllWebs[SPWebName])
{
SPList list = web.Lists[SPListName];
SPListItemCollection listitems = web.Lists[SPListName].Items;


int count = 0;

for (int i = list.Items.Count - 1; i >= 0; i--)
{
listitems.Delete(i);
count++;
}
MessageBox.Show(count+" rows deleted successfully");

}
}
}
catch (Exception ee)
{
MessageBox.Show("Incorrect Data");
}
}

Display Sharepoint list items in a grid view.

This article describes how to display sharepoint list items in a grid view, i.e C# windows application gridview.
Start a C# windows application and add a Button and a DataGridView to display the list items.
Call the following method on the button click event.

private void ViewData()
{
string camlquery;

string SPSiteName = "http://localhost";
string SPWebName = "";
string SPListName = "some_list";

try
{
using (SPSite site = new SPSite(SPSiteName))
{
using (SPWeb web = site.AllWebs[SPWebName])
{
SPList list = web.Lists[SPListName];
SPQuery query = new SPQuery();

//mention the query as you want

camlquery = " ";
query.Query = camlquery;
SPListItemCollection listitems = list.GetItems(query);
DataTable dt = listitems.GetDataTable();
dataGridView1.Visible = true;
dataGridView1.DataSource = dt;

MessageBox.Show(listitems.Count + " rows");

}
}
}
catch (SPException ee)
{
MessageBox.Show("Incorrect data entered");
}
}

Don’t forget to add the Microsoft.SharePoint reference.