Setting value for Taxonomy field produces Value does not fall within the expected range
-
10-12-2019 - |
Question
I have a custom ASPX
page where the user inputs data and clicks Save to add new item to the list. The field My Department
is a Managed Metadata field
(single choice). The user sets the value for this field through TaxonomyWebTaggingControl
control. The problem happens when the value is supposed to be set to the new list item:
string departmentField = "My_x0020_Department"; //internal field name
SPListItem item = myList.Items.Add();
item[SPBuiltInFieldId.Title] = this.documentTitleTextBox.Text;
item[departmentField] = this.DepartmentTaxonomy.Text; //error fires here
item.Update();
The error is ArgumentException: Value does not fall within the expected range.
If the user does not specify the value for the department, i.e. if this.DepartmentTaxonomy.Text = string.Empty;
then there is no error.
Solution 2
OK, I found the solution to the problem, though not the cause. Instead of just banging down the value as string this.DepartmentTaxonomy.Text
, I really had to go an extra mile to manually create TaxonomyFieldValue
object.
So, getting the TaxonomyFieldValue is done in this method:
public TaxonomyFieldValue GetTaxonomyValue(SPList list, string fieldName, string fieldValue)
{
string[] fieldValueParts;
TaxonomyField taxonomyField;
TaxonomyFieldValue taxonomyFieldValue;
fieldValueParts = fieldValue.Split(TaxonomyField.TaxonomyGuidLabelDelimiter);
taxonomyField = list.Fields[fieldName] as TaxonomyField;
taxonomyFieldValue = new TaxonomyFieldValue(taxonomyField);
taxonomyFieldValue.TermGuid = fieldValueParts[1];
taxonomyFieldValue.Label = fieldValueParts[0];
return taxonomyFieldValue;
}
And here's how I used this method:
string departmentField = "My_x0020_Department"; //internal field name
SPListItem item = myList.Items.Add();
item[SPBuiltInFieldId.Title] = this.documentTitleTextBox.Text;
item[departmentField] = this.GetTaxonomyValue(myList, departmentField, this.DepartmentTaxonomy.Text);
item.Update();
This resolved the issue.
OTHER TIPS
Instead of
item[departmentField] = this.DepartmentTaxonomy.Text;
try
item[departmentField] = this.DepartmentTaxonomy.Label;