SharePoint List C# Part 1

Here I'm going to show you how you can use the SharePoint object model to read SharePoint list using C#.

To do this in your custom webpart or feature first you have to add the reference to Microsoft.Sharepoint.dll (Then in your code use "using Microsoft.Sharepoint;"). And also if you are going to run the program, you have to be in the server.


Read SharePoint List



public void getData()
{
    // choose your site
    string strUrl = "http://mysite:5050/";
    using (SPSite site = new SPSite(strUrl))
    {
        using (SPWeb web = site.OpenWeb())
        {
            // choose the list
            SPList list = web.Lists["insert your list Name"];
            SPQuery myquery = new SPQuery();
            myquery.Query = "insert your query here";
            // if you dosent insert query (myquery.Query ="") you will get all items
            SPListItemCollection items = list.GetItems(myquery);
            foreach (SPListItem item in items)
            {
                // check the item for null
                if (item != null)
                {
                    // do something
                }
            }
        }
    }
}
Adding Item


string strUrl = "http://mysite:5050/";
            using (SPSite site = new SPSite(strUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPListItemCollection listItems = web.Lists["List_Name"].Items;
                    SPListItem item = listItems.Add();
                    item["Title"] = "New Item Title";
                    item.Update();
                }
            }
You can use U2U CAML Query Builder to write queries you want.

If you want to get information from lookup field, please refer SharePoint List C# Part 2, for delete items please refer Delete items from SharePoint list.

 

 

Comments