Skip to content
September 9, 2015 / kiranpatils

How to set a value for a Name Value List

Challenge:

This might sound newbie question. But I’ve been asked this question multiple times ranging from Beginner till expert. So, thought to blog it. Basically, You have Name value field in Sitecore, and you would like to set its value using API.

You have same question? Or not now. But have no clue and curious to know? How? Then this post is for you:

Solution:

We faced this challenge somewhere in April, and during that time we did a quick search and we were unable to find anything helpful. Then one of our Best Friend and Colleague — Sheetal Jain came up with following solutions:

NameValueListField nameValueListField = childItem.Fields["NAMEVALUELISTFIELDNAME"];
if (nameValueListField != null)
{
	nameValueListField.NameValues.Add("NAME1", "VALUE1");
	nameValueListField.NameValues.Add("NAME2", "VALUE2");
}
if (String.IsNullOrEmpty(childItem.Fields["NAMEVALUELISTFIELDNAME"].Value))
{
	childItem.Fields["NAMEVALUELISTFIELDNAME"].Value = "NAME1=VALUE1";
}
else
{
	childItem.Fields["NAMEVALUELISTFIELDNAME"].Value = childItem.Fields["NAMEVALUELISTFIELDNAME"].Value + "&"  + "NAME2=VALUE2";
}

Then before writing this post. Thought to do quick search again and found this post : https://community.sitecore.net/developers/f/8/t/202

  var db = Sitecore.Configuration.Factory.GetDatabase("master");
      var item = db.GetItem("{8A8E427B-9162-4680-AE69-239217F5B9AB}");

      //Initialize data
      var data = new NameValueCollection();
      data.Add("name1", "value1");
      data.Add("name2", "value2");
      data.Add("name3", "value3");
      data.Add("name4", "value4");
      
      using (new Sitecore.SecurityModel.SecurityDisabler())
      {
        item.Editing.BeginEdit();
        try
        {
          //where data is NameValueCollection
          //where '$' is divider 
          item["NameList"] = StringUtil.NameValuesToString(data, "&");
        }
        finally
        {
          item.Editing.EndEdit();
        }
      }

Which is also neat way to do the same. So, now you’ve three ways to solve one problem! Feel free to select whichever you like!

Happy Sitecoring! 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: