Reputation: 4100
For the sitecore item testItem
how can I make sure that this item has the field "Title
".
I am asking because I am creating some fields in an item's template programmatically. So a field should not be created again if it already exists.
Because with this code I can get if the field has some value or not.
testItem["Title"]
testItem.Fields["Title"]
Upvotes: 1
Views: 11495
Reputation: 524
To save having to check the field against your testItem more than once you could cast to a field and then: check the field for null, that it has a value and then retrieve the value.
The advantage here is that if you need to access the field in several places you don't have to retrieve from testItem each time.
e.g.
Field titleField = testItem.Fields["Title"];
if (titleField != null && titleField.HasValue)
{
//do something with value
string fieldValue1 = titleField.Value;
//or (see intellisense for params)
string fieldValue2 = titleField.GetValue(true);
}
Upvotes: 0
Reputation: 328
Code below will return value, including Standard or Default value for the field:
if (testItem.Fields["Title"] != null && testItem.Fields["Title"].HasValue)
{
string title = testItem["Title"].Value;
}
Upvotes: 2
Reputation: 4118
Please check this code, you are checking if item, fields collection and field value is not null
if(testItem!= null && testItem.Fields != null && testItem.Fields["Value"] != null)
{
string name = testItem.Fields["Title"].Value;
}
Upvotes: 8