Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers

up vote 0 down vote accepted

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.

share|improve this answer
add comment

Instead of item[departmentField] = this.DepartmentTaxonomy.Text;
try item[departmentField] = this.DepartmentTaxonomy.Label;

share|improve this answer
    
DepartmentTaxonomy is of type TaxonomyWebTaggingControl and this control does not contain the Label property. –  Boris Dec 26 '12 at 8:48
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.