关于在Share point 2010 中保存SPFieldLookupValue类型到一个List中的问题

在share point 中,有时字段的类型是lookup的,那么将会从另外的一个list中进行相应的连接,这是如果保存string等类型,将会报一个错,

 Invalid data has been used to update the list item. The field you are trying to update may be read only.

这个错误看起来莫名其妙,但实际上是有一定道理的,因为这个字段可以认为是表外键一样的存在。

那应该怎么办呢?这里我写了一个方法:

复制代码
public static SPFieldLookupValue GetLookupFieldFromValue(string lookupValue, string lookupSourceColumn, SPList lookupSourceList)
        {
            SPFieldLookupValue value = null;
            SPQuery query = new SPQuery();
            query.Query = "<Where><Eq><FieldRef Name='" + lookupSourceColumn + "'/><Value Type='Text'>" + lookupValue + "</Value></Eq></Where>";

            SPListItemCollection listItems = lookupSourceList.GetItems(query);
            if (listItems.Count > 0)
                value = new SPFieldLookupValue(listItems[0].ID, lookupValue);                
            return value;
        }
复制代码

  这个方法中,lookupValue是你获得的需要查找的字符串,lookupSourceColumn是拥有内容主体的list(或者就认为是外键表),lookupSourceList是list。

这时在进行保存:

item["demo"]=GetLookupFieldFromValue("abc","Title",web.List["Demo"]);

//item["user"]=spuser;
item.update();

  正常保存就可以了。当然如果权限不够的话需要加上:

SPSecurity.RunWithElevatedPrivileges(delegate()
            {
//......
});

  相对于spuser类型的字段,直接拿到spuser保存就可以了。

原文地址:https://www.cnblogs.com/tdskee/p/3305751.html