In this post we will discuss about how to get value of selected fields from a SharePoint list using SharePoint object model.
Also you can check out my previous posts on:
Below is the code that will retrieve selected value of an item:
using (SPSite site = new SPSite("http://SiteURL"))
using (SPWeb web = site.RootWeb)
SPList list = web.GetList("Employees");
SPListItem item = list.GetItemByIdSelectedFields(5, "Name", "Age", "Department");
String employeeName = (String)item["Name"];
Int employeeAge = Convert.ToInt32( item["Age"]);
string employeeDept = (String)item["Department"];
Here GetItemByIdSelectedFields(Int32, String) method took first parameter as Int32 which is the ID number of the item and 2nd parameter is an array of the internal names of the fields from the item.
Each time an item is added to a list, it is given a 1-based integer ID that is one greater than the ID of the previous item added. When an item is deleted from a list, its ID number is not reused.
Here the list item whose id is 5 will be retrieved but only 3 defined fields (Name, Age, Department).
Retrieve all the fields:
If you want all the fields of the list item, use the GetItemByIdAllFields(Int32) method. Its only parameter is the item ID.
SPListItem item = list.GetItemByIdAllFields(5);
Here it will retrieve all the fields whose ID is 5.