SharePoint List C# Part 2

In my previous post SharePoint List C# Part 1, I wrote how to retrieve data from SharePoint list. In this post also I'm going to show you how to retrieve data from SharePoint list which has look up fields. You can use this code in your custom webpart ot feature.




public void getData()
{
    // choose the site
    SPSite site = new SPSite("http://mysite:5050/");
    SPWeb web = site.OpenWeb();
    // choose the list "Task Categories"
    SPList list = web.Lists["Task Categories"];
    SPListItemCollection itemCollection;
    // pass query to get status
    SPQuery oQuery = new SPQuery();
    // get all items
    oQuery.Query = "";
    itemCollection = list.GetItems(oQuery);
    foreach (SPListItem item in itemCollection)
    {
        if (item != null)
        {
            // get data in "Sub Category(s)" lookup column
            if (item["Sub Category(s)"] != null)
            {
                SPFieldLookupValueCollection subItemColl = ((SPFieldLookupValueCollection)item["Sub Category(s)"]);
                foreach (var subitem in subItemColl)
                {
                    // do something
                }
            }
        }
    }
}

 

Comments