Sunday, October 31, 2010

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";

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.

No comments:

Post a Comment