Search This Blog

Tuesday 29 May 2012

Get only specified fields from SharePoint 2010 Lists

Hi All,

Here, I have explained how to get only specific fields from SharePoint 2010 Lists. Generally we get the listitem by querying(using SPQuery) and it returns collection of SPListItems with all fields of the list unless the user specify the ViewFields property.

Below i have given sample, where i used ViewFields property to select only 4 fields from the specified list.


Code Snippet:

using (SPSite osite = new SPSite("http://chesgh201tw1v:1605"))
            {
                using (SPWeb oweb = osite.OpenWeb())
                {
                    // Build a query.
                    SPQuery oquery = new SPQuery();
                    oquery.Query = string.Concat(
                                   "<Where><Eq>",
                                      "<FieldRef Name='DocumentType'/>",
                                      "<Value Type='Lookup'>Job Aid</Value>",
                                   "</Eq></Where>");

                    oquery.ViewFields = string.Concat(
                                        "<FieldRef Name='Title' />",
                                        "<FieldRef Name='DocumentType' />",
                                        "<FieldRef Name='AllowMultiple' />",
                                        "<FieldRef Name='ShowHeader' />");

                    oquery.ViewFieldsOnly = true; // Fetch only the data that we need.

                    // Get data from a list.
                    SPList list = oweb.Lists.TryGetList("Section Type Master");
                    SPListItemCollection items = list.GetItems(oquery);

                    // Print a report header.
                    Console.WriteLine("{0,-20}  {1,-20}  {2,-20}  {3,-20}",
                       "Title", "Document Type", "Allow Multiple", "Show Header");

                    //// Print the details.
                    foreach (SPListItem item in items)
                    {
                        Console.WriteLine("{0,-20}  {1,-20}  {2,-20}  {3,-20}",
                           item["Title"], item["DocumentType"], item["AllowMultiple"], item["ShowHeader"]);
                    }
                }
            }

Here i get 4 fields (Title, DocumentType, AllowMultiple and ShowHeader)

Output:













No comments:

Post a Comment