Getting a SharePoint Field Value In C#
Someone asked me this morning when doing a code review of my code how I got a field value. They were not looking very closely. Here is how I do it, although there are 50,000 other ways of doing it.
This is my getFieldValue helper method, that will be called at other instance points throughout the code.
- public static string getFieldValue(SPListItem listItem, string fieldName)
- {
- string text = string.Empty;
- if (fieldName == string.Empty)
- {
- return text;
- }
- try
- {
- object myObj = listItem[fieldName];
- return ((myObj != null) ? myObj.ToString() : string.Empty);
- }
- catch
- {
- return string.Empty;
- }
- }
Once the helper method is defined, then it can be consumed in something like a foreach loop to return SharePoint list items based on conditions. If the condition is not met, it will return null.
- private SPListItem getItemText(SPListItemCollection spItems, string text)
- {
- foreach (SPListItem item in spItems)
- {
- if (getFieldValue(item, this.myList.myColumn) == text)
- {
- return item;
- }
- }
- return null;
- }
Articles & Research
SharePoint Security
SharePoint Development
SharePoint Architecture
Claims Authentication
Forefront For SharePoint
AIS / Dynamics GP
Team Foundation Server
Pex And Moles
ISA/TMG/IAG/UAG
DPM
Cardspace
Research Methodology
Rural ICT Development
Numerical Analysis
Multi-Level Research
Knowledge Management
Personal/Off-Topic
Very nice method and a good coding practice. Nice work.
Does not always work. If i create a column “project”, then delete it, then create a column “project” again, it’s field name is actually now “project0″ despite visibly showing project.
skip all that – it’s still funky. the reason is that display name and internal name arent always the same…and this only works when they are the same. Something like this might be a bit more stable if columns ever change (i’ve crunched the code for brevity):
SPListItemCollection qItems = splc["ListName"].GetItems(query);
…
foreach (SPListItem spli in qItems)
{
fieldValue = spli[spli.Fields.GetField("ColName").InternalName];
}